我遇到了一个具体问题,我已将其转换为以下 Minimal, Complete, and Verifiable example .
#include <iostream>
class Foo {
public:
Foo(int v) : val(v) {}
int get_val() const
{
return val;
}
private:
int val;
};
class Parent {
public:
Parent() : member(0) {}
const Foo& get_member() const
{
return member;
}
protected:
Foo member;
};
// Nothing above this line should be changed
class Child : public Parent
{
public:
// This doesn't work (compile error)
//Child() Parent::member(1) {}
// Nor does this (also a compile error)
//Child() this->member(1) {}
};
int main()
{
Child x;
std::cout << x.get_member().get_val() << std::endl;
return 0;
}
这个例子演示了我在一个更大的软件项目中遇到的问题,我从一个外部库继承但需要直接初始化父的成员变量之一。
不幸的是,Parent 类没有参数化其成员初始化的构造函数。
如果 Parent
类具有以下形式的构造函数
Parent(int val) : member(val) {}
然后我可以编写一个 Child
构造函数作为
Child() Parent::Parent(1) {}
但我不是这样的。
问题:是否可以将父类的成员变量的初始化推迟到继承的类中?如果是,怎么办?
最佳答案
Is it possible to defer the initialization of a parent's member variable to an inherited class? If so, how?
父类的成员变量要么在其成员初始化列表中初始化,要么在构造函数体中初始化。子类不能在其初始化列表中初始化父类的成员变量——这是语言所不允许的。看起来,您能做的最好的事情就是在子类的构造函数体中设置父类成员的值。
例子:
struct foo
{
int a;
};
struct bar : foo
{
bar() : a(0) {} // Not allowed
};
但是
struct bar : foo
{
bar() { a = 0; } // Allowed
};
关于c++ - 是否可以在不修改父类的情况下将成员变量初始化推迟到继承类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45598810/