我了解到我永远不能访问私有变量,只能使用类中的get函数.但是为什么我可以在复制构造函数中访问它?
例:
Field::Field(const Field& f)
{
pFirst = new T[f.capacity()];
pLast = pFirst + (f.pLast - f.pFirst);
pEnd = pFirst + (f.pEnd - f.pFirst);
std::copy(f.pFirst, f.pLast, pFirst);
}
Run Code Online (Sandbox Code Playgroud)
我的声明:
private:
T *pFirst,*pLast,*pEnd;
Run Code Online (Sandbox Code Playgroud) 我们都知道protected从基类指定的成员只能从派生类自己的实例访问.这是标准的一个特性,这已在Stack Overflow上多次讨论:
但似乎有可能用成员指针来解决这个限制,因为用户chtz 向我展示:
struct Base { protected: int value; };
struct Derived : Base
{
void f(Base const& other)
{
//int n = other.value; // error: 'int Base::value' is protected within this context
int n = other.*(&Derived::value); // ok??? why?
(void) n;
}
};
Run Code Online (Sandbox Code Playgroud)
为什么这可能,它是一个想要的功能或实施中的某个地方或标准的措辞?
从评论中出现了另一个问题:如果Derived::f用实际调用Base,是不确定的行为?
c++ protected access-specifier member-pointers language-lawyer