以下代码会产生编译错误:
'BaseTest::_protMember' : cannot access protected member declared in class 'BaseTest'
为什么我不能访问我的 class SubTest
中的成员变量 _protMember
,即使它是 protected ?
class BaseTest
{
public:
BaseTest(){};
BaseTest(int prot)
{
_protMember = prot;
};
protected:
int _protMember;
};
class SubTest : public BaseTest
{
// followup question
SubTest(const SubTest &subTest)
{
_protMember = subTest._protMember; // this line compiles without error
};
SubTest(const BaseTest &baseTest)
{
_protMember = baseTest._protMember; // this line produces the error
};
};
后续问题:
为什么在添加的复制构造函数中我可以访问另一个实例的 protected 成员?
最佳答案
您只能访问protected
来自您自己的基类实例的成员......不是作为参数提供给您的成员。这完全是关于 OO 封装的。如果没有这个限制,正在构建的对象可能会使 baseTest&
的不变量无效。参数。
换句话说,您的 SubTest
可以决定 protected
的用途与另一个成员对同一成员的使用冲突的成员 BaseTest
派生类(比如 SubTest2 : BaseTest
)。如果你的SubTest
代码被允许摆弄其他对象的数据,它可能会使 SubTest2
中的不变量无效对象,或者获取一些值 - 在预期的封装中 - 只意味着暴露给 SubTest2
和(可选 - 见下文)SubTest2
衍生品。
Followup question: Why is it, that in the added copy constructor I can access protected members of another instance?
SubTest(const SubTest& x); // can access x._protMember
SubTest(const BaseTest& x); // cannot access x._protMember
上面的相同见解解释了为什么允许这样做:复制构造函数得到一个 SubTest&
。而不仅仅是从 BaseTest
派生的任何旧对象, 而这个构造函数显然在 SubTest
中抽象。 SubTest
假定编码器熟悉预期的设计/封装 SubTest
提供,并且复制构造函数可以绕过并在另一个上强制执行后置条件/不变量SubTest&
对象也是。 (您正在从一个对象复制,该对象本身可能是由完全相同的函数复制构造的,因此在“*this
”端而不是参数引用端保护它根本没有太多保护,甚至忽略您可能想要/需要该访问权限的所有合理理由)。
有可能 SubTest
-derived 对象将被意外传递给 SubTest
复制构造函数(“切片”),但即使对于那种情况,SubTest&
类可以控制进一步派生的对象是否可以用 _protMember
做任何意外的事情- 添加 private
using BaseTest::_protMember;
声明是否要“最终确定”对 _protMember
的访问并禁止任何派生类使用它。
关于c++ - 为什么我的对象不能访问公共(public)基类中定义的另一个对象的 protected 成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17717027/