c++ - 关于c++的派生问题

标签 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;
        }
    };

最佳答案

A 的构造函数在 B 之前运行,并且隐式或显式地,前者构造 A 的所有实例,包括 a 成员。因此 B 不能在 a 上使用构造函数,因为该字段已经构造。您尝试使用的表示法准确地表明要在 a 上使用构造函数,而在这一点上它是不可能的。

关于c++ - 关于c++的派生问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1303890/

相关文章:

c++ - 派生类中指向基类的指针 vector

c# - 从对象获取属性

C++:基类中的字符串参数在派生类解构时解构

c++ - 基类中的派生类实例

c++ - DarkGDK颜色渐变代码

c++ - 给定一个数及其根值,求一个数的 n 次方根

c++从继承链获取对外部成员的访问

c++ - 是否有 std::equal 的安全替代方案?

c++ - 在 C++ 中包含的 C header 中转发声明枚举

c++ - 正确包含基类和子类(派生类)的头文件?