gpt4 book ai didi

C++ 保护 : fail to access base's protected member from within derived class

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:17 35 4
gpt4 key购买 nike

不可否认,这个问题的标题听起来与你的邻居迈克反复问的问题几乎一模一样。我发现很多问题的措辞相同,但没有一个是我的问题。

首先,对于这个问题的上下文,我想澄清几点:

1,c++访问控制是基于类而不是基于实例。因此,下面的代码是完全有效的。

class Base
{
protected:
int b_;

public:
bool IsEqual(const Base& another) const
{
return another.b_ == b_; // access another instance's protected member
}
};

2,我完全理解为什么以下代码无效 - 另一个可以是兄弟实例。

class Derived : public Base
{
public:
// to correct the problem, change the Base& to Derived&
bool IsEqual_Another(const Base& another) const
{
return another.b_ == b_;
}
};

现在是时候提出我真正的问题了:

假设在 Derived 类中,我有一个 Base 实例数组。所以实际上,Derived 是一个 Base(IS-A 关系),而 Derived 由 Base(复合关系)组成。我从某个地方读到这(指的是 IS-A 和 Has-A 的设计)是一种设计味道,我一开始就不应该有这样的场景。好吧,例如,分形的数学概念可以通过 IS-A 和 Has-A 关系来建模。但是,让我们暂时忽略对设计的意见,只关注技术问题。

class Derived : public Base
{
protected:
Base base_;

public:
bool IsEqual_Another(const Derived& another) const
{
return another.b_ == b_;
}

void TestFunc()
{
int b = base_.b_; // fail here
}
};

报错信息已经很清楚的说明错误了,所以你的回答就不用再重复了:

Main.cpp:140:7: error: ‘int Base::b_’ is protected int b_; ^ Main.cpp:162:22: error: within this context int b = base_.b_;

实际上,根据以下两个事实,上面的代码应该可以工作:

1,C++ 访问控制基于类而不是基于实例(因此,请不要说我只能访问 Derived 的 b_;我不能访问独立的 Base 实例的 protected 成员 - 它基于类) .

2,错误消息说“在此上下文中”——上下文是派生的(我试图从派生中访问 Base 实例的 protected 成员。这是 protected 成员的特性——它应该能够从在 Base 或从 Base 派生的任何东西中。

那么为什么编译器给我这个错误?

最佳答案

访问规则原则上可以为这种特殊情况提供豁免,其中已知 Base最派生类,即对象的动态类型。但这会使事情变得复杂。 C++ 已经足够复杂了。

一个简单的解决方法是在 Base 中提供一个 static protected 访问器函数。

一个更 hack'ish 的解决方法是使用成员指针臭名昭著的类型系统漏洞。但如果必须坚持基本设计,我会选择 static 函数。因为我认为当生成的代码一开始就很难正确,而且维护人员也很难理解时,节省几次击键没有多大意义。


具体例子:

class Base
{
protected:
int b_;

static
auto b_of( Base& o )
-> int&
{ return o.b; }

public:
auto IsEqual( const Base& another ) const
-> bool
{
return another.b_ == b_; // access another instance's protected member
}
};

关于C++ 保护 : fail to access base's protected member from within derived class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34588930/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com