【发布时间】:2021-09-18 10:58:52
【问题描述】:
AFAIK 类类型的 const 对象导致其所有成员也为 const。而且指向普通对象的指针不能指向const 对象。
在这个例子中,我试图理解指向类成员的指针:
struct Foo{
int value_ = 1024;
};
int main(){
int Foo::* ptr = &Foo::value_; // ptr is a pointer to any non-const non-static integer member data
Foo f;
++(f.*ptr);// ok
Foo const cf;
// ++(cf.*ptr); // error. OK
std::cout << cf.*ptr << '\n';
std::cout << "\ndone!\n";
}
如您所见,ptr 是一个指向 Foo 类型为 int 的非静态非常量成员数据的指针,这意味着它不能指向 const 整数成员数据。
-
cf是const类型的Foo类对象,我们知道常量对象的成员本身就是常量,为什么允许这样做:std::cout << cf.*ptr << '\n'; // why allowed? -
cf的value_现在是常量,因为cf是const那么为什么允许将指针ptr绑定到该常量成员数据?
【问题讨论】:
-
这是对类属性的引用,为什么 const 应该关心?你只是对编译器说
get the attribute with this offset -
@AlbertoSinigaglia:但是如果你尝试修改它,它会编译失败:
++(cf.*ptr);产生错误。 -
是的,因为您正在尝试编辑一个 const 字段......事情应该像这样工作:(1)你好,这是我的对象(2)请转到这个偏移量 [@987654341 @] (3) 做你必须做的事……在 (3) 编译器检查你是否能做你想做的事
-
允许绑定,不允许变异 - "...cv 限定规则与对象运算符的成员相同,但有一个附加规则:指向该成员的指针引用可变成员不能用于修改 const 对象中的该成员;..." en.cppreference.com/w/cpp/language/operator_member_access
-
@RichardCritten:非常感谢!