C++ 转换运算符错误?

标签 c++ operator-overloading operator-keyword

运算符在类声明中重载:

class Asdf{

    operator float() const;                 
    Asdf operator+(const Asdf&) const;
    Asdf operator+(float);

}

int main()

{
    Asdf object1, object2, object3;

    //Receiving error: "more than one operator '+' matches these operands"
    object1= object2 + object3;

    _getch();
    return 0;
}

错误:

   :error C2666: 'Asdf::operator +' : 3 overloads have similar conversions

   :could be 'Asdf Asdf::operator +(float)'

   :'Asdf Asdf::operator +(const Asdf &) const'

当我删除所有与重载的 float 转换运算符一起使用的转换时,代码会正确编译。

最佳答案

隐式转换运算符往往会引起此类歧义,尤其是与隐式构造函数结合使用时。

来自 C++ 编码标准:

  1. Consider overloading to avoid implicit type conversions.

Do not multiply objects beyond necessity (Occam's Razor): Implicit type conversions provide syntactic convenience (but see Item 40). But when the work of creating temporary objects is unnecessary and optimization is appropriate (see Item 8), you can provide overloaded functions with signatures that match common argument types exactly and won't cause conversions.

Not all change is progress: Implicit conversions can often do more damage than good. Think twice before providing implicit conversions to and from the types you define, and prefer to rely on explicit conversions (explicit constructors and named conversion functions).

其中很多涉及提供隐式转换可能导致的效率和意外行为,但函数重载引起的歧义错误包含在提供隐式转换运算符和/或构造函数时很容易遇到的副作用中。

解决方案:使您的运算符(operator)明确或尽量避免提供它。这可能很方便,但它可能会引起像这样令人讨厌的意外(编译器错误实际上是最不讨厌的)。

关于C++ 转换运算符错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12665494/

相关文章:

C++ 常量静态 char* 数组

c++ - 为什么我的赋值运算符不能用于自赋值?

c++ - 带运算符的函数模板

ruby-on-rails - => 运算符与 = 运算符

c++ - 如何在 std::cout 中既不以科学形式也不以定点表示法输出 float ?

c++ - 按位或运算符

c++ - 如何重载赋值运算符以满足ob1=ob2=ob3(ob1、ob2、ob3是同一类的对象)

swift - 错误 : '...' is not a prefix unary operator

c++ - 实现 '<' 运算符

C++ 通用 Unicode