[英]Illegal member initialization in C++
class ZooAnimal {
public:
virtual void draw();
int resolveType() {return myType;}
protected:
int myType;
};
class Bear : public ZooAnimal {
public:
Bear (const char *name) : myName(name), myType(1){}
void draw(){ };
private:
std::string myName;
};
void main()
{
}
When I am compiling above code I am geeting following error 当我编译上面的代码时,我正在跟踪错误
error C2614: 'Bear' : illegal member initialization: 'myType' is not a base or member 错误C2614:'熊':非法成员初始化:'myType'不是基础或成员
Why I am geeting above error, as we can access protected member from derived calss? 为什么我会在错误之上纠结错误,因为我们可以从派生的calss访问受保护的成员?
You can't initialize base class member in derived class initializer lists. 您无法在派生类初始化列表中初始化基类成员。
You'll need to provide a constructor to the base class: 您需要为基类提供构造函数:
class ZooAnimal {
public:
ZooAnimal(int type) : myType(type) {}
virtual void draw();
int resolveType() {return myType;}
protected:
int myType;
};
and call it from the derived class: 并从派生类中调用它:
class Bear : public ZooAnimal {
public:
//here//
Bear (const char *name) : ZooAnimal(1), myName(name) {}
void draw(){ };
private:
std::string myName;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.