c++限定符错误
我已经开始为我需要的库编写一些代码。以下代码给我一个错误
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&中 节点::运算符=(const 节点&)': graph.cpp:16: 错误: 传递 'const 节点”作为“luint”的“this”参数 node::getID()' 丢弃限定符
我的代码有什么问题吗?
谢谢,
I have begun writing some code for a library I need. The following code gives me an error
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();
}
which is the following:
graph.cpp: In member function 'node&
node::operator=(const node&)':
graph.cpp:16: error: passing 'const
node' as 'this' argument of 'luint
node::getID()' discards qualifiers
Did I do anything wrong with the code?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
inNode
被声明为const
,这意味着您只能调用其上的const
成员函数。您必须将const
修饰符添加到getID
来告诉编译器它不会修改该对象:Your
inNode
is declared to beconst
, which means you can only invokeconst
member functions on it. You'll have to add theconst
modifier togetID
to tell the compiler that it won't modify the object:在您的operator=函数中,inNode是常量。函数
getID
不是常量,因此调用它会丢弃inNode的常量性。只需将 getID 设置为常量即可:In your operator= function, inNode is constant. The function
getID
is not constant, so calling it is discarding the constness of inNode. Just make getID const:您需要将 getID() 设置为常量。
You need to make getID() const.