喜欢这段代码
class Try
{
public:
Try() = default;
int i = 0;
};
class B1 : private Try
{
public:
B1() = default;
using Try::Try();
using Try::i;
};
class C1 : public B1
{
public:
Try a; //tell me:'Try' is a private member of 'Try'
void print()
{std::cout << i << std::endl;}
//Access to this I is allowed;
};
Try a是本地对象,不是C1的一部分,为什么会出错?
只要是私有(private)继承的直接基类,是不是就不能在其派生类中定义间接基类对象了?是构造函数无法使用还是其他原因?
最佳答案
the Try a is a local object , not a part of C1, why error?
通过在类C1
的上下文中编写Try a;
,名称查找通常总是从本地范围扫描到全局范围。因此,第一个匹配项将是 B1::Try
,由于私有(private)继承,C1
无法访问它。
修复很简单,只需提示编译器您“真正”的意思,即通过编写例如::尝试一下;
.
关于c++ - private继承的直接基类阻止派生类定义间接基类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65609813/