c++ - 在 C++ 中编写复制构造函数时出错

标签 c++

我正在尝试为一个类编写一个复制构造函数,但我收到了这两条错误消息,我无法破译。有人可以告诉我我做错了什么吗?

class Critter
    {

    public:
        Critter(){}
        explicit Critter(int hungerLevelParam):hungerLevel(hungerLevelParam){}
        int GetHungerLevel(){return hungerLevel;}

        // Copy Constructors
        explicit Critter(const Critter& rhs);
        const Critter& operator=(const Critter& rhs);

    private:
        int hungerLevel;
    };

Critter::Critter(const Critter& rhs)
    {
    *this = rhs;
    }

const Critter& Critter::operator=(const Critter& rhs)
    {
    if(this != &rhs)
        {
        this->hungerLevel = rhs.GetHungerLevel(); // ERROR: object has type qualifier not compatible with member function
        }
    return *this;
    }

int _tmain(int argc, _TCHAR* argv[])
    {
    Critter aCritter2(10);
    Critter aCritter3 = aCritter2; // ERROR : No suitable copy constructor
    Critter aCritter4(aCritter3);
    return 0;
    }

最佳答案

你需要 int GetHungerLevel() const {return hungerLevel;}

否则,不允许使用常量引用 rhs 调用 GetHungerLevel()

此外,您不能使用显式 复制构造函数进行复制初始化,只能直接初始化:Critter aCritter3(aCritter2);

可能您想使复制构造函数成为非显式的,而不是必须更改 aCritter3 的定义,但是您的决定。

关于c++ - 在 C++ 中编写复制构造函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10885737/

相关文章:

C++11 正则表达式不匹配任何内容

c++ - 如何在 C++ 中重载 ofstream 运算符?

c++ - 在 QString 中连接 STL string+int+int+int

c++ - exe中 Unresolved external symbol 错误,但dll中没有

C++ 避免重新定义需要返回多态类型的代码

c++ - 存在重载命名空间函数时需要 std::qualifier 吗?

c++ - 如何使用 C++ 访问文本文件中的特定值

c++ - 使用 SDL 在 OpenGL 表面上绘制文本

c++ - 为什么 std::exception 没有 move 构造函数?

c++ - 通过引用重载多个函数对象