使用初始化列表(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!")
    {
    }
}

相关文章