私有继承的直接基类防止派生类定义间接基类的对象

问题描述

喜欢这个代码

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 的一部分,为什么会出错?

只要是私有继承的直接基类,难道不能在其派生类中定义间接基类对象吗?是构造函数不能用还是其他原因?

解决方法

Try a 是一个本地对象,不是 C1 的一部分,为什么会出错?

通过在类 Try a; 的上下文中编写 C1,名称查找通常总是从本地范围扫描到全局范围。因此,第一个匹配项将是 B1::Try,由于私有继承,C1 无法访问该匹配项。

修复很简单,只需向编译器提示您“真正”的意思,即通过编写例如::Try a;