当有多个合适的操作符时,设置首选操作符

Set prefered operator when more than one are suitable

本文关键字:操作符 设置      更新时间:2023-10-16

我有一个名为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)那样对它进行强制转换。