对运算符进行试验会导致运算符错误不明确

Experimenting with operators results in ambiguous operator error

我正在研究重载运算符。

当我使用 classes 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

但是如果我用

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

(准备下一个 class FLOAT)

编译器抱怨:"operator INTEGER::int() const" 和 "operator INITEGER::double() const" 在

之间不明确
  i2 = i1 + s1;

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

请点亮我的心...

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

恕我直言,您应该避免使用 'funny' 转换运算符,因为它们会导致各种代码意外运行,例如

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

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

谢谢!

插入这个片段时,一切都恢复正常 - 直到下一个障碍!^^

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

  return iValue + iValue2;
  }