子类无法继承超类字段

Subclasses failing to inherit superclass fields

我有一个名为 A 的 class,其定义如下:

class A {
public:

    int time;
    A *next; 
    someFunc();
    A();
    virtual ~A();
};

我有一个 A 的子class,叫做 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) { }

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

我正在 Eclipse 中开发这个程序并使用 makefile 来构建它。我建造 B.o 的线路是:

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

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

您为参数使用了相同的名称,因此它们是 "hiding" 成员。你可以在构造函数体中做这样的事情:

this->time = time;
this->next = next;

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

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();
};

class 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();
};

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

您可以添加一个构造函数来为 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) { }

或者如果您不能为 A 添加构造函数,则在 B 的构造函数中分配它们:

B::B(int time, A *next, int state, Foo *id) : state(state), ID(id) {
    this->time = time;
    this->next = next;
}