代码之家  ›  专栏  ›  技术社区  ›  J. Cal

子类无法继承超类字段[重复]

  •  -1
  • J. Cal  · 技术社区  · 7 年前

    我有一个名为a的类,定义如下:

    class A {
    public:
    
        int time;
        A *next; 
        someFunc();
        A();
        virtual ~A();
    };
    

    我有一个子类a,叫做B,定义如下:

    #include "A.h"
    
    class B : public A {
    public:
    
        int state;
        Foo *ID;
        someFunc();
        B(int time, A *next, int state, Foo *id);
        virtual ~B();
    };
    

    B的构造函数定义为:

    B::B(int time, A *next, int state, Foo *id) : time(time), next(next), state(state), ID(id) { }
    

    当我构建程序时,我得到一个错误,即类B没有名为“time”或“next”的字段我确保在B.h文件和B.cpp文件中都包含了A.h,但这似乎没有什么区别。值得注意的是,可以识别类B中的someFunc()。我在B.cpp中定义了一个不同于a类版本的主体。在B.h中的声明中,Eclipse有一个标记提醒我它“隐藏”了a::someFunc(),所以我知道B至少继承了这一点。

    我正在Eclipse中开发这个程序,并使用makefile来构建它。我对B.o.大楼的看法是:

    B.o: B.cpp B.h
        g++ -c -Wall -g B.cpp
    

    我还尝试在第一行末尾添加A.h,但没有任何效果。我是否遗漏了可能导致此错误的内容?

    4 回复  |  直到 7 年前
        1
  •  1
  •   songyuanyao    7 年前

    您不能初始化基类的成员,这应该是基类的责任。

    您可以添加一个构造函数,用于初始化 A :

    class A {
    public:   
        int time;
        A *next; 
        someFunc();
        A();
        virtual ~A();
        A(int time, A* next);
    };
    
    A::A(int time, A *next) : time(time), next(next) { }
    

    然后

    B::B(int time, A *next, int state, Foo *id) : A(time, next), state(state), ID(id) { }
    

    或将其分配到 B 的构造函数,如果无法为添加构造函数 A. :

    B::B(int time, A *next, int state, Foo *id) : state(state), ID(id) {
        this->time = time;
        this->next = next;
    }
    
        2
  •  0
  •   Marker    7 年前

    您对参数使用了相同的名称,因此它们“隐藏”了成员。您可以在构造函数主体中执行以下操作:

    this->time = time;
    this->next = next;
    
        3
  •  0
  •   Mark Ransom    7 年前

    构造函数初始化列表只能初始化自己的类成员,而不能初始化其父类的成员。您通常要做的是使用父级的构造函数来初始化它们。

    class A {
    public:
    
        int time;
        A *next; 
        someFunc();
        A(int time, A *next) : time(time), next(next) {}
        virtual ~A();
    };
    
    class B : public A {
    public:
    
        int state;
        Foo *ID;
        someFunc();
        B(int time, A *next, int state, Foo *id) : A(time, next), state(state), ID(ID) {}
        virtual ~B();
    };
    
        4
  •  0
  •   Some programmer dude    7 年前

    班级 B 成员是否来自 A . 但它们不在构造函数初始值设定项列表的范围内。您必须创建 A. 使用要传递给的参数的构造函数 A. :

    class A {
    public:
    
        int time;
        A *next; 
        someFunc();
    
        A(int time, A* next)
            : time(time), next(next)
        {}
    
        virtual ~A();
    };
    
    class B : public A {
    public:
    
        int state;
        Foo *ID;
        someFunc();
    
        B(int time, A *next, int state, Foo *id)
            : A(time, next), ID(id)
        {}
    
        virtual ~B();
    };