I have a Cartesian coords class, where I've attempted to overload some operators, however when building I get a fatal error about how the operator has multiple defined symbols.
class Cartesian
public:
int x,y;
Cartesian operator/=(const int64_t denominator)
{
return { x /= denominator, y /= denominator };
}
Cartesian operator =(const Cartesian& c)
{
return { x = c.x, y = c.y };
}
Cartesian operator (const Cartesian& c)
{
return { x c.x, y c.y };
}
friend Cartesian operator (const Cartesian& c1, const Cartesian& c2);
};
Cartesian operator (const Cartesian& c1, const Cartesian& c2) { return { c1.x c2.x, c1.y c2.y }; };
Can someone help identify the mistake I've made here?
CodePudding user response:
This is same operator
Cartesian operator (const Cartesian& c)
{
return { x c.x, y c.y };
}
friend Cartesian operator (const Cartesian& c1, const Cartesian& c2);
You can have one or another, but not both. Member operators are assuming that their first operand is one of enclosing class. So both declarations would generate same mangled name. Some 90s compilers could miss that and problem would appear only on linking stage or would not be revealed at all if operator was used, I even had bad luck to acquire a book where sample code contained such mistake.
CodePudding user response:
Below is the working example that have overloaded operator
for addition and also have overloaded operator<<
for printing out the current point values. Your mistake was that you were defining operator
twice, first inside the class and then outside also. Instead just define it outside the class as shown below.
#include <iostream>
class Cartesian
{
public:
//Overload operator for adding Cartesian instances
friend Cartesian operator (const Cartesian& c1, const Cartesian& c2);
//Overload operator<< for printing out Cartesian's x and y values
friend std::ostream& operator<<(std::ostream& os, const Cartesian& obj);
int x,y;
void setXY(int px, int py)
{
x = px;
y = py;
}
};
Cartesian operator (const Cartesian& c1, const Cartesian& c2)
{
return { c1.x c2.x, c1.y c2.y };
}
std::ostream& operator<<(std::ostream& os, const Cartesian& obj)
{
std::cout<<obj.x<<" "<<obj.y;
}
int main()
{
std::cout<<"Hello World"<<std::endl;;
Cartesian point1, point2;
point1.setXY(5,10);
std::cout<<"point1's coordinates are: "<<point1<<std::endl;
point2.setXY(15, 20);
std::cout<<"point2's coordinates are: "<<point2<<std::endl;
Cartesian resultingPoint = point1 point2;
std::cout<<"resultingPoint's coordinates are: "<<resultingPoint<<std::endl;
return 0;
}