I'm overloading operator * and + to read some class' variables from files. I have written the following code:
class X {
public:
double getLength(void) {
return length;
}
void setLength( double len ) {
length = len;
}
// Overload + operator to add two Box objects.
X operator*(X temp){
X temp1;
temp1.length = this->length * temp1.length;
return temp1;
}
X operator*(int num){
X temp1;
temp1.length = this->length * num;
return temp1;
}
X operator+(X temp){
X temp1;
temp1.length = this->length + temp1.length;
return temp1;
}
private:
double length; // Length of a box
};
// Main function for the program
int main() {
X ob1; // Declare Box1 of type Box
X ob2; // Declare Box2 of type Box
X ob3; // Declare Box3 of type Box
double result = 0.0; // Store the volume of a box here
ob2.setLength(6.0);
ob3.setLength(12.0);
ob1 = ob2 + 2*ob3;
ob1 = ob2*2 + ob3;
ob1 = (ob2 + 2) *ob3;
cout << "length of Box : " << ob1.getLength() <<endl;
return 0;
}
But when I try to compile the above code, I am getting following error:
main.cpp: In function 'int main()':
main.cpp:48:17: error: no match for 'operator*' (operand types are 'int' and 'X')
ob1 = ob2 + 2*ob3;
~^~~~
main.cpp:50:15: error: no match for 'operator+' (operand types are 'X' and 'int')
ob1 = (ob2 + 2) *ob3;
~~~~^~~
main.cpp:27:8: note: candidate: 'X X::operator+(X)'
X operator+(X temp){
I cant understand the error in my code. Please help me to solve the error.