c++ - Operator overloading error "binary '+' : no operator found which takes a left-hand operand" -
class cfruit { private: string m_name; public: string getname() const; cfruit(string name = "noname"); };
the fruitsalad represented in class cfruitsalad:
class cfruitsalad { //overloaded operators friend ostream& operator <<(ostream& out, const cfruitsalad& f); friend cfruitsalad operator +(const cfruit& f1, const cfruit& f2); private: string m_fruitsalad; public: cfruitsalad(string content = ""); string getname() const; };
now when use write this:
cfruit f1("apple"); cfruit f2("orange"); cfruit f3 ("banana"); cfruitsalad fs; fs = f1 + f2 + f3; //this line generates error cout << "content: " << fs << endl;
when compiled program following error received: error c2678: binary '+' : no operator found takes left-hand operand of type 'cfruitsalad' (or there no acceptable conversion)
why error occur , how solve it?
fs = f1 + f2 + f3;
no matter order of evaluation (assume f2+ f3
evaluated @ first), first return object of cfruitsalad
based on declaration here:
friend cfruitsalad operator +(const cfruit& f1, const cfruit& f2);
now, next +
operation, adding object of cfruit
object of cfruitsalad
, don't have overloaded version takes 1 cfruit
, 1 cfruitsalad
, causes error.
you need change implementation of overloaded operator+
(don't overload operators if not meaningful imho).
Comments
Post a Comment