导出关于c ++的问题

use*_*749 1 c++ derived-class

为什么我无法访问基类A是B类初始化列表中的成员?

   class A
    {
    public:
        explicit A(int a1):a(a1)
        {
        }
        explicit A()
        {
        }

    public:
        int a; 

    public:
        virtual int GetA()
        {
            return a;
        }
    };

    class B : public A
    {
    public:
        explicit B(int a1):a(a1) // wrong!, I have to write a = a1 in {}. or use A(a1)
        {
        }
        int GetA()
        {
            return a+1;
        }
    };

    class C : public A
    {
    public:
        explicit C(int a1):a(a1)
        {
        }
        int GetA()
        {
            return a-1;
        }
    };
Run Code Online (Sandbox Code Playgroud)

Ale*_*lli 6

A的构造函数在B之前运行,并且隐式或显式地,前者构造A的所有实例,包括a成员.因此B不能使用构造函数a,因为该字段已经构造.您尝试使用的符号表示准确使用构造函数a,此时它只是不可能.


pil*_*row 6

为了建立Alex的答案,你可以通过控制它的结构来初始化基类' "a"成员,如下所示:

class B : public A
{
public:
    explicit B(int a1) : A(a1) { }  // This initializes your inherited "a"
    ...
};
Run Code Online (Sandbox Code Playgroud)

请注意,我正在构建上面的基类(大写"A"),而不是尝试直接初始化其继承的成员(小写"a",从您的示例中绘制).