问题描述
我在C ++中收到以下错误:
I am getting the following error in C++:
Class Base
{
protected:
int var1;
public:
Base()
{
var1=0;
}
}
class Child : public Base
{
int chld;
public:
Child() : var1(0)
{
chld=1;
}
}
我觉得我所做的是根据OO协议。
这里 var1
是Base类的数据成员,protected作为访问说明符。所以它可以被继承,它会变成私人的孩子。
I feel what I have done is as per OO protocol. Here var1
is a data member of Base class with protected as the access specifier. So It can be inherited and it would become private in child.
不明白我为什么会收到错误?
推荐答案
它不能用于错误消息为您提供的确切原因:您只能将初始化程序列表与直接成员或基类一起使用。
It doesn't work for the exact reason the error message provides you: you can only use initializer lists with direct members or base classes.
在你的情况下,你甚至不需要初始化 var1
,因为 Base :: Base()
将是由 Child
的构造函数调用,它将 var1
设置为 0
。
In your case, you don't even need to initialize var1
, since Base::Base()
will be called by Child
's constructor, which will set var1
to 0
.
如果你想要一个不同的值,你必须重载 Base
构造函数并明确地调用它:
If you want a different value, you'll have to overload Base
constructor and call it explicitly:
class Base
{
protected:
int var1;
public:
Base() : var1(0)
{
}
Base(int x) : var1(x)
{
}
};
class Child:public Base
{
int chld;
public:
Child(): Base(42) , chld(1)
{
}
};
这篇关于错误C2614:'ChildClass':非法成员初始化:'var1'不是基础或成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!