当有多个合适的操作符时,设置首选操作符
Set prefered operator when more than one are suitable
我有一个名为mc_int
的类,它实际上是一个int,具有一些特殊功能。设置operator int()
:
mc_int::operator int() {
return value; //int mc_int::value - the real int value of the class
}
但是当我尝试cout<<
类时,我必须始终将类转换为int (cout<<(int)mc_int_instance
),因为我得到错误:
多个操作符"<<"匹配这些操作数。
同样,这可能是由于类还定义了 <<
操作符。在这里该怎么做?
如果你使用的是c++ 11,你可以使用explicit
关键字,这样你就必须显式地转换为int
。更多信息在这里:
explicit mc_int::operator int()
现在,当您使用它时,应该使用您定义的<<
操作符方法,并且它应该不再对编译器有歧义。如果你想使用int类型,只需像使用static_cast<int>(the_object)
那样对它进行强制转换。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 嵌套在类中时无法设置成员数据
- 需要帮助设置在C++中使用的Potrace
- 如何在自删除后将对象设置为nullptr
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何在Ubuntu中使用cmake设置qt4
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 如何在boost beast http请求中设置http头
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 如何在24位SDL_Surface上设置像素的颜色
- 重载c++中的下标[]操作符来设置类(量词)的大小
- c++赋值操作符,如何将一个对象设置为等于一个新对象的实例
- 当操作符地址可以设置为普通变量时,为什么要求从函数返回地址?
- 检查结构体是否为NULL或未设置,即使它的有操作符相等
- 当有多个合适的操作符时,设置首选操作符
- 如何重载子索引操作符,使其在获取项和设置项时表现不同