c++ - C++中的非法成员初始化

标签 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()
{
   
}

当我编译上面的代码时,我遇到了以下错误

error C2614: 'Bear' : illegal member initialization: 'myType' is not a base or member

为什么我会收到上述错误,因为我们可以从派生类访问 protected 成员?

最佳答案

您不能在派生类初始化列表中初始化基类成员。

您需要为基类提供一个构造函数:

class ZooAnimal {
public:

    ZooAnimal(int type) : myType(type) {}

    virtual void draw();
    int resolveType() {return myType;}
    protected:
    int myType;
};

并从派生类中调用它:

class Bear : public ZooAnimal {
public:
                            //here//
Bear (const char *name) : ZooAnimal(1), myName(name) {}

void draw(){ };
private:
    std::string myName;
};

关于c++ - C++中的非法成员初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10294731/

相关文章:

c++ - 嵌入式 Visual C++/为什么我的符号未定义?

C++ Lint : detect improper pass by value

c++ - for 循环和点的问题

C++ 32 位应用程序试图使用 64 位 MFC DLL

c++ - 目标名称 "C:/path/to/lib/file.lib"已保留或对某些 CMake 功能无效

c# - 如何计算文件的增量,即更改的文件部分

c++ - boost 几何 : legacy objects adaptation

c++ - 为什么QT的iOS组件占用那么大的磁盘空间?

c# - 将它们从 CLI 传递到 C# 时 float 发生变化

c++ - 如何可移植地检测编译器是否支持 <iostream> vs <iostream.h>