子类无法继承超类字段

时间:2018-02-15 03:17:31

标签: c++ class inheritance makefile subclass

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

class A {
public:

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

我有一个名为B的A的子类,其定义如下:

#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&#39>的构造函数定义为:

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

当我构建程序时,我得到一个错误,即B类没有名为" time"或者"接下来。"我确保我将A.h包含在B.h文件以及B.cpp文件中,但似乎没有任何区别。值得注意的是,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 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

您为参数使用了相同的名称,因此他们“隐藏”了成员。你可以在构造函数体中做这样的事情:

+1.00000000 -0.50000000 +0.00000000 +0.50000000
+0.10000000 -0.05000000 -0.00000000 +0.05000000
+0.01000000 -0.00500000 +0.00000000 +0.00500000
+0.00100000 -0.00050000 -0.00000000 +0.00050000
+0.00010000 -0.00005000 -0.00000000 +0.00005000
+0.00001000 +0.00000000 +0.00000500 +0.00001000
+0.00000100 -0.00000050 -0.00000000 +0.00000050
+0.00000010 -0.00000005 +0.00000000 +0.00000005

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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