使用初始化列表(C++)初始化父级的受保护成员 [英] Initialize parent's protected members with initialization list (C++)

查看:45
本文介绍了使用初始化列表(C++)初始化父级的受保护成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用子类的构造函数的初始化列表来初始化在父类中声明为受保护的数据成员?我无法让它工作.我可以解决它,但如果我不必这样做就好了.

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++)初始化父级的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆