[英]Passing the derived class constructor parameter to a protected member
I'm trying to practice some polymorphism and i got into some issues. 我正在尝试练习一些多态性,但遇到了一些问题。
Here's my code : 这是我的代码:
class A{ //the base
public:
A(){}
virtual void Log(){};
virtual ~A(){};
private:
protected:
int __value;
};
class B : public A{ //the derived
public:
B(int value):__value(value){} //here's the problem
void Log() override{
std::cout<<__value<<"\n";
}
~B(){};
};
At that lines the error said : "class 'B' does not have any field named '__value'". 那行的错误说:“类'B'没有任何名为'__value'的字段”。 It does work if i will do it in this way : 如果我将以这种方式做到这一点,它将起作用:
class A{
public:
A(){}
virtual void Log(){};
virtual ~A(){};
private:
protected:
int __value;
};
class B : public A{
public:
B(int value){
__value=value;
}
void Log() override{
std::cout<<__value<<"\n";
}
~B(){};
};
I know what i've tried works while i'm accesing the private members, but I want to know if there is some way to make the first attempt work too. 我知道我加入私有成员时尝试过的方法是可行的,但是我想知道是否有某种方法也可以使第一次尝试也可行。
Thanks! 谢谢!
C++ does not work this way. C ++无法以这种方式工作。 Only a class's constructor can initialize its members. 只有类的构造函数才能初始化其成员。
Only A
's constructor can initialize its class member. 只有A
的构造函数可以初始化其类成员。 That's what a constructor's job is. 这就是构造函数的工作。 A derived class cannot initialize its base class's members, only it's own class members. 派生类不能初始化其基类的成员,而只能初始化自己的类成员。 A base class only initializes the base class's members. 基类仅初始化基类的成员。 A derived class's constructor can initialize only its own class's members. 派生类的构造函数只能初始化其自己的类的成员。
What you need to do is add a constructor to A
, perhaps a protected constructor, with a parameter that initializes the class member with the parameter: 您需要做的是向A
(可能是受保护的构造函数)添加一个构造函数,并使用一个参数初始化该类成员的参数:
class A {
// ...
A(int value) : __value{value} {}
// ...
};
And have the derived class's constructor explicitly invoke this constructor. 并让派生类的构造函数显式调用此构造函数。
B(int value) : A{value}
{
}
In some situations you can also delegate the constructor, as an alternative. 在某些情况下,您也可以委派构造函数作为替代。 This should be covered in the advanced C++ chapters of your C++ book. 这应该在C ++书籍的高级C ++章节中介绍。
PS You should use modern C++'s uniform initialization syntax, with {...}
instead of (...)
. PS您应该使用现代C ++的统一初始化语法,并使用{...}
而不是(...)
。 If you're using an older C++ book that doesn't cover uniform initialization syntax, you should get a more recent book. 如果您使用的是较旧的C ++书籍,但没有涵盖统一的初始化语法,则应该获得较新的书籍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.