问题描述
是否可以使用子类的构造函数的初始化列表来初始化在父类中声明为受保护的数据成员?我无法让它工作.我可以解决它,但如果我不必这样做就好了.
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!")
{
}
};
当我尝试这个时,编译器告诉我:类‘Child’没有任何名为‘something’的字段".这样的事情可能吗?如果是这样,语法是什么?
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++)初始化父级的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)