使用初始化列表(C ++)初始化父级的受保护成员 [英] Initialize parent's protected members with initialization list (C++)
问题描述
是否可以使用子类的构造函数的初始化列表来初始化在父类中声明为protected的数据成员?我不能让它工作。
Is it possible to use the initialization list of a child class' constructor to initialize data members declared as protected in the parent class? I can't get it to work. I can work around it, but it would be nice if I didn't have to.
一些示例代码:
class Parent
{
protected:
std::string something;
};
class Child : public Parent
{
private:
Child() : something("Hello, World!")
{
}
};
当我尝试这个时,编译器告诉我:class'Child'没有名为'东西'。这样的东西可能吗?如果是,语法是什么?
When I try this, the compiler tells me: "class 'Child' does not have any field named 'something'". Is something like this possible? If so, what is the syntax?
非常感谢!
推荐答案
这是不可能的你的方式描述。你必须添加一个构造函数(可以被保护)到基类中转发它。类似的东西:
It is not possible in the way you describe. You'll have to add a constructor (could be protected) to the base class to forward it along. Something like:
class Parent
{
protected:
Parent( const std::string& something ) : something( something )
{}
std::string something;
}
class Child : public Parent
{
private:
Child() : Parent("Hello, World!")
{
}
}
这篇关于使用初始化列表(C ++)初始化父级的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!