结构体与结构体引用的成员选择
在课程 13.7 —— 结构体、成员与成员选择简介中,我们介绍了如何使用成员选择运算符(.)从结构体对象中选择成员:
#include <iostream>
struct Employee
{
int id {};
int age {};
double wage {};
};
int main()
{
Employee joe { 1, 34, 65000.0 };
// 使用成员选择运算符(.)从结构体对象中选择成员
++joe.age; // Joe 过生日了
joe.wage = 68000.0; // Joe 升职了
return 0;
}
由于对象引用的行为与对象本身相同,也可以使用成员选择运算符(.)从结构体引用中选择成员:
#include <iostream>
struct Employee
{
int id{};
int age{};
double wage{};
};
void printEmployee(const Employee& e)
{
// 使用成员选择运算符(.)从结构体引用中选择成员
std::cout << "Id: " << e.id << '\n';
std::cout << "Age: " << e.age << '\n';
std::cout << "Wage: " << e.wage << '\n';
}
int main()
{
Employee joe{ 1, 34, 65000.0 };
++joe.age;
joe.wage = 68000.0;
printEmployee(joe);
return 0;
}
结构体指针的成员选择
不过,不能直接对指向结构体的指针使用成员选择运算符(.):
#include <iostream>
struct Employee
{
int id{};
int age{};
double wage{};
};
int main()
{
Employee joe{ 1, 34, 65000.0 };
++joe.age;
joe.wage = 68000.0;
Employee* ptr{ &joe };
std::cout << ptr.id << '\n'; // 编译错误:不能对指针使用 operator.
return 0;
}
对于普通变量或引用,可以直接访问对象。但指针保存的是地址,因此必须先解引用指针获取对象,才能对它进行操作。 因此,可以通过下面的方式从结构体指针访问成员:
#include <iostream>
struct Employee
{
int id{};
int age{};
double wage{};
};
int main()
{
Employee joe{ 1, 34, 65000.0 };
++joe.age;
joe.wage = 68000.0;
Employee* ptr{ &joe };
std::cout << (*ptr).id << '\n'; // 不太美观但可行:先解引用 ptr,再使用成员选择
return 0;
}
不过这种写法不太美观,尤其是必须给解引用操作加括号,确保它的优先级高于成员选择操作。
为了让语法更简洁,C++ 提供了从指针选择成员的运算符(->)(有时也称为箭头运算符),用于选择指针所指对象的成员:
#include <iostream>
struct Employee
{
int id{};
int age{};
double wage{};
};
int main()
{
Employee joe{ 1, 34, 65000.0 };
++joe.age;
joe.wage = 68000.0;
Employee* ptr{ &joe };
std::cout << ptr->id << '\n'; // 更好的方式:使用 -> 从指向对象的指针中选择成员
return 0;
}
从指针进行成员选择的运算符(->)与成员选择运算符(.)作用相同,但会在选择成员前隐式解引用指针。 因此,ptr->id 等价于 (*ptr).id。
箭头运算符不仅更容易输入,也更不容易出错,因为间接访问由运算符隐式完成,不必担心优先级问题。 因此,通过指针访问成员时,应始终使用 -> 运算符,而不是 . 运算符。
最佳实践
使用指针访问成员时,应使用指针成员选择运算符(->),而不是成员选择运算符(.)。
链式访问 operator->
如果通过 operator-> 访问的成员是指向类类型的指针,就可以在同一个表达式中再次使用 operator-> 访问该类类型的成员。
下面的示例说明了这一点(感谢读者 Luna):
#include <iostream>
struct Point
{
double x {};
double y {};
};
struct Triangle
{
Point* a {};
Point* b {};
Point* c {};
};
int main()
{
Point a {1,2};
Point b {3,7};
Point c {10,2};
Triangle tr { &a, &b, &c };
Triangle* ptr {&tr};
// ptr 是指向 Triangle 的指针,而 Triangle 包含指向 Point 的指针成员
// 要访问 ptr 指向的 Triangle 中 Point c 的成员 y,下面两种写法等价:
// 使用 operator. 访问
std::cout << (*(*ptr).c).y << '\n'; // 很丑!
// 通过 operator-> 访问
std::cout << ptr -> c -> y << '\n'; // 美观多了
}
连续使用多个 operator->(例如 ptr->c->y)时,表达式可能难以阅读。在成员与 operator-> 之间添加空格(例如 ptr -> c -> y),可以更容易区分被访问的成员和运算符。
混合使用指针与非指针成员访问
成员选择运算符始终作用于当前选中的变量。如果成员中混合使用指针和普通变量,就会看到 . 和 -> 连续使用的情况:
#include <iostream>
#include <string>
struct Paw
{
int claws{};
};
struct Animal
{
std::string name{};
Paw paw{};
};
int main()
{
Animal puma{ "Puma", { 5 } };
Animal* ptr{ &puma };
// ptr 是指针,使用 ->
// paw 不是指针,使用 .
std::cout << (ptr->paw).claws << '\n';
return 0;
}
请注意,对于 (ptr->paw).claws, 由于 operator-> 和 operator. 都按从左到右的顺序求值,因此不需要括号,但加上括号可以略微提高可读性。