【问题标题】:Experimenting with operators results in ambiguous operator error用运算符试验会导致模棱两可的运算符错误
【发布时间】:2016-01-08 11:10:58
【问题描述】:

我正在玩重载运算符。

当我使用 INTEGER 和 STRING 类时,一切运行良好。

 class INTEGER {
  private:
    int iValue;

  public:
    INTEGER() {
      iValue = 0;
      }

    int& operator=  (int const& iParam) {
      return iValue = iParam;
      }

    friend ostream& operator<< (ostream& os, const INTEGER& obj)  {
      return os << obj.iValue << endl;
      }

    operator int    () const {
      return iValue;
      }

    operator string () const {
      ostringstream os;
      os << iValue;
      return string(os.str().c_str());
      }
    };


  class STRING {
  private:
    string  strValue;

  public:
    STRING () {
      strValue = "";
      }

    string& operator= (string const& strParam) {
      return strValue = strParam;
      }

    friend ostream& operator<< (ostream& os, const STRING& obj) {
      return os << obj.strValue.c_str() << endl;
      }

    operator int() const {
      istringstream ss(strValue);
      int iValue;
      ss >> iValue;
      return iValue;
      }
  };


int main() {  
    INTEGER i1, i2;
    STRING  s1, s2;

    i1 = 1;    
    s1 = "2";

    i2 = i1 + s1;
    s2 = i2;

    cout << i1 << s1 << i2 << s2;

    return 0;
  }

输出:

1 2 3 3

但是如果我用

扩展我的类 INTEGER
operator double    () const {
  return (double)iValue;
  }

(为下一堂FLOAT做准备)

编译器在“operator INTEGER::int() const”和“operator INITEGER::double() const”之间不明确

  i2 = i1 + s1;

我不懂我的编译器,从未使用过浮点值。 i1 和 i2 来自 INTEGER 类,s2 来自 STRING 类,并且有一个 int()- 运算符。

请点亮我的心灵...

【问题讨论】:

  • int&amp; operator= (int const&amp; iParam) { iValue = iParam; } 您没有返回值,因此行为是未定义。
  • 你确定它说的是“INTEGER::init”而不是“INTEGER::int”吗?我认为您的问题是,如果没有双重运算符,您的代码是:i2.operator=(i1.operator int() + s1.operator int());。使用双重运算符,它无法决定是否使用它,或者i2.operator=(static_cast&lt;int&gt;(i1.operator double() + static_cast&lt;double&gt;(s1.operator int()));
  • 这就是 C++ 社区中许多人回避强制转换运算符的原因。假设您的代码确实编译了。首先,正如所指出的,由于未从声明为返回值的函数返回值,因此行为未定义。但其次,您能否确定在运行程序时将调用哪个运算符,即不使用调试器?这就是问题所在——使用强制转换运算符的代码多次调用我们不希望调用的函数。

标签: c++ operator-overloading


【解决方案1】:

您尚未定义operator+(INTEGER,STRING),因此您的编译器必须使用内置运算符之一+。它可以使用int+int 或double+int,因为STRING 有一个将int 和INTEGER 转换为int 和double 的运算符。但这两个选择是模棱两可的。

恕我直言,您应该避免使用“有趣”的转换运算符,因为它们允许各种代码意外运行,例如

STRING s;
std::cout << std::setw(s) << "oops";

而是直接定义算术运算符。

【讨论】:

    【解决方案2】:

    谢谢!

    当插入这个片段时,一切都很好 - 直到下一个障碍!^^

    const int operator+(const string& strValue) {
      istringstream ss(strValue);
      int iValue2;
      ss >> iValue2;
    
      return iValue + iValue2;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 2010-12-10
      • 1970-01-01
      相关资源
      最近更新 更多