This question already has answers here:
Initialize parent's protected members with initialization list (C++)

(4个答案)


7年前关闭。




我很难在Google上找到热门歌曲。
struct a {
    float m_x;
    float m_z;
public:
    a(float x): m_x(x) {}
};

class b : public a {
    b(float z): m_z(z) {}
};

在clang 3.2上:
error: member initializer 'm_z' does not name a non-static data member or base class
    b(float z): m_z(z) {}

最佳答案

不,您不能直接从初始化列表中初始化基类成员。这是因为初始化顺序以这种方式进行

C++标准n3337 § 12.6.2/10



因此,您可以在基类中指定一个构造函数(可以 protected ),并在派生类的初始化列表(should be preferred)中使用该构造函数,也可以在派生类ctor主体中分配给基类成员(不同的行为,不同的作用和效率也较低-您正在分配给默认的初始化成员(已有值))。

在前一种情况下,您可以这样编写:

struct A {
    float m_x;
    float m_z;
    A(){}
protected:
    A(float x): m_x(x) {}
};

class B : public A {
public:
    B(float z) : A(z) {}
    // alternatively
    // B(float z) {
    //     m_x = z;
    // }
};

int main(){
    B b(1);
    return 0;
}

09-10 00:58
查看更多