受保护成员访问只有在没有得到其地址时才有效
Protected member access works only when not getting its address
我有多重继承(类A
是基类,B
从A
派生,C
从B
派生)。A
有一个受保护的成员属性,我尝试在C
中以不同的方式访问它。
考虑以下代码:
#include <iostream>
using namespace std;
class A {
protected:
int x;
public:
A() : x(42) {}
};
class B : public A {
};
class C : public B {
protected:
typedef B Precursor;
public:
void foo() {
cout << Precursor::x << endl;
cout << this->x << endl;
}
int get() {
return Precursor::x;
}
int* getPtr() {
// error: ‘int A::x’ is protected
// error: within this context
// error: cannot convert ‘int A::*’ to ‘int*’ in return
return &Precursor::x;
//return &this->x; // this works
}
};
int main() {
C obj;
obj.foo();
cout << obj.get() << endl;
cout << obj.getPtr() << endl;
}
在C::foo()
和C::get()
中,Precursor::x
可以访问x
。然而,&Precursor::x
不起作用。为什么呢?this->x
和&this->x
总是工作的。
Clang error message:
cpp-inheritance.cpp:34:22: error: 'x' is a protected member of 'A'
return &Precursor::x;
^
cpp-inheritance.cpp:7:6: note: must name member using the type of the current context 'C'
int x;
^
cpp-inheritance.cpp:34:10: error: cannot initialize return object of type 'int *' with an
rvalue of type 'int A::*'
return &Precursor::x;
^~~~~~~~~~~~~
2 errors generated.
当&
操作符用于形式为C::m
的限定名时,其中C
是一个类,m
是一个非静态成员,它返回一个指向C::*T
类型成员的指针,其中T
是m
的类型。这是一种特殊情况,它覆盖了返回作为&
操作数的表达式指针的默认行为。
要获得指向C::m
的指针,其中C是基类,您必须使&
的操作数不是限定名,例如&this->C::m
或&(C::m)
。
参考:c++ 14,5.3.1/3
如果操作数是限定id,命名某个类型为T的类C的非静态成员m,则结果的类型为"指向类型为T的类C成员的指针",并且是指定C::m的右值
由于Precursor::x不是类的静态成员,因此无法获取其地址。您需要声明实例,并获取实例的地址成员。这就是为什么这个->x工作:1. C继承B,它有从B继承的元素x和2.
相关文章:
- 是否可以在C++中获取 CHAR 的有效十六进制地址?
- 自 C++17 年以来,具有正确地址和类型的指针始终是有效的指针
- 如何检查STD :: Next(x)指向C 中的有效地址
- C++检查有效的 IP 地址或 IP
- 在UDP套接字上多次调用Connect()以发送到不同的目标地址 - 有效
- 当 std::vector 增长时,其中元素的地址不再有效
- 为什么数组元素长度的地址计算可被 2 的幂整除更有效
- WSAStringToAddress 认为"1.2.3"是有效的 IP 地址
- C++最大有效内存地址
- 通过写入全局llvm的地址从执行引擎外部初始化全局llvm值有效吗
- 我们可以检查一个指针以确保它是一个有效的地址吗
- 存储IPv4/IPv6地址的有效方式
- 从任何内存地址读取UInt32的最有效方法
- 字符 * 名称 = "Duncan" 怎么可能 ;如果指针只能保存地址,是否有效?
- 获取函数的地址并在编译时丢弃它:这是有效的c++吗?
- 局部变量的返回地址和程序仍然有效
- 带有有效地址的c++删除指针
- visualstudio2008-如何确定字符串是否是C++中的有效IPv6地址
- 有效的IP地址在unix上的c/c++库
- 受保护成员访问只有在没有得到其地址时才有效