1

我已经开始为我需要的库编写一些代码。以下代码给了我一个错误

class node {
public:
    node() { }
    node(const node&);
    ~node() { }

    luint getID() { return this->ID; }
    node& operator=(const node&);
protected:
    luint ID;
    std::vector<node*> neighbors;
};
node::node( const node& inNode) {
    *this = inNode;
}

node& node::operator=(const node& inNode) {
    ID = inNode.getID();
}

如下:

graph.cpp:在成员函数'node& node::operator=(const node&)'中:graph.cpp:16:错误:将'const node'作为'luint node::getID()'的'this'参数传递会丢弃限定符

我对代码做错了什么吗?

谢谢,

4

3 回答 3

3

inNode被声明为const,这意味着你只能const在它上面调用成员函数。您必须添加const修饰符以getID告诉编译器它不会修改对象:

luint getID() const { return this->ID; }
于 2010-10-13T19:50:04.517 回答
1

在您的 operator= 函数中, inNode 是恒定的。该函数getID不是常量,因此调用它就是丢弃 inNode 的常量。只需将 getID 设为 const:

luint getID() const { return this->ID; }
于 2010-10-13T19:51:36.157 回答
0

您需要将 getID() 设为常量。

于 2010-10-13T19:50:49.917 回答