有没有办法把它作为常量传递
is there a way to pass this as const?
我有一类项和返回其大小的函数。我有一个运算符==,它获取类类型的2个常量参数,并返回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,我必须使其成为友元并将对象作为常量引用传递,或者有没有方法告诉size将类类型this作为常量???谢谢你的帮助。
很可能您忘记将size
成员函数限定为const:size_t size() const { return /* compute/return size */; }
另一种选择是,您确实在某个地方将CardDeck
拼写为Cardeck
(错误消息中的拼写)。
相关文章:
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 遇到新行时,有没有办法停止istream_iterator
- 有没有一种方法可以在编译时获得作用域类名
- conan有没有办法导出一个空目录
- 为什么乘以常量有符号整数分数没有优化?
- 有没有办法声明一个公共静态常量,该常量将使用 constexpr 在源文件中定义(有什么区别)?
- 有没有办法在类实例中存储编译时常量?
- 有没有办法为静态对象成员定义一个符合开关标准的常量?
- 有没有办法在我的通用功能路由器设计中支持"常量引用"作为功能签名参数?
- 有没有一种通用方法来"unprotect"静态常量成员?
- 有没有办法禁止将临时绑定到常量引用
- 有没有更好/安全的方法将shared_ptr的非常量引用强制转换为基类
- 有没有办法不警告 gcc 中开关缺少"COUNT"枚举常量?
- 有没有办法把它作为常量传递
- 有没有办法声明函数的输入参数必须是常量引用
- 有没有办法"reconst"非常量字符?
- 有没有办法强制Protocol Buffer使用常量字段大小