user5598651
user5598651

Reputation:

Experimenting with operators results in ambiguous operator error

I am playing around with overloading operators.

All is running fine when I was working with the classes INTEGER and 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;
  }

Outputs:

1 2 3 3

But if I expand my class INTEGER with

operator double    () const {
  return (double)iValue;
  }

(preparings for the next class FLOAT)

the compiler bleats with: ambiguous between "operator INTEGER::int() const" and "operator INITEGER::double() const" at

  i2 = i1 + s1;

I don't understand my compiler, never used a floating point value. i1 and i2 are from the class INTEGER and s2 is from class STRING and has a int()- operator.

Please light my mind...

Upvotes: 0

Views: 78

Answers (2)

user5598651
user5598651

Reputation:

Thank you!

When inserting this snip, all is fine again - until next obstacle!^^

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

  return iValue + iValue2;
  }

Upvotes: 0

Walter
Walter

Reputation: 45434

You have not defined operator+(INTEGER,STRING), so your compiler must do with one of the builtin operators +. It can either use int+int or double+int, since STRING has a conversion operator to int and INTEGER to both int and double. But these two choices are ambiguous.

IMHO, you should avoid 'funny' conversion operators, since they allow all sorts of code to work unexpectedly, for example

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

Instead define the arithmetic operators directly.

Upvotes: 3

Related Questions