【发布时间】:2016-01-10 20:29:47
【问题描述】:
我有一类项目和一个返回其大小的函数。 我有 operator ==,它获取类 类型的 2 个 const 参数并返回 item1.size() == item2.size () 的结果。 size 函数是非参数函数,只需要隐藏这个参数。
问题是当我尝试在类的 const 引用上使用 size 时,它给了我一个错误:
'function' : cannot convert 'this' pointer from 'type1' to 'type2'
The compiler could not convert the this pointer from type1to type2.
This error can be caused by invoking a non-const member function on a const object. Possible resolutions:
Remove the const from the object declaration.
Add const to the member function.
关于我的问题的那段代码:
bool operator==(const CardDeck& deck1, const CardDeck& deck2){
if (deck1.size() != deck2.size()) {
return false;
}
//...
}
错误:
'unsigned int CardDeck::size(void)' : cannot convert 'this' pointer from 'const CardDeck' to 'Cardeck&'
如果我希望该 size 将对象作为 const,我必须使它成为朋友并将对象作为 const 引用传递,或者有没有办法告诉 size 将类类型作为常量? 感谢您的帮助。
【问题讨论】:
-
你做了
CardDeck::size() const吗? -
据我了解,将其设为 const 意味着将其参数设为 const,而这里仅此而已。写 const CardDeck::size() 只意味着返回的值(不是通过引用,而是它的副本)将是 const,这并不意味着什么,我错了吗?这就是为什么我问是否有办法告诉编译器这是方法大小的常量。
-
您可以通过在函数声明之后但在其主体之前添加
const关键字来创建整个函数const。与返回类型或参数无关。