在C++中,運算符重載是一種允許你自定義已有運算符行為的方法。你可以為類或結構體重載運算符,使其具有類似于內置類型的行為。以下是一些常見運算符的重載示例:
class MyClass {
public:
MyClass a, b;
MyClass operator+(const MyClass& other) const {
MyClass result = *this;
result.a += other.a;
result.b += other.b;
return result;
}
};
class MyClass {
public:
int a, b;
MyClass operator-(const MyClass& other) const {
MyClass result = *this;
result.a -= other.a;
result.b -= other.b;
return result;
}
};
class MyClass {
public:
int a, b;
MyClass operator*(const MyClass& other) const {
MyClass result;
result.a = a * other.a;
result.b = b * other.b;
return result;
}
};
class MyClass {
public:
int a, b;
MyClass operator/(const MyClass& other) const {
MyClass result;
result.a = a / other.a;
result.b = b / other.b;
return result;
}
};
class MyClass {
public:
int a, b;
MyClass& operator=(const MyClass& other) {
if (this != &other) {
a = other.a;
b = other.b;
}
return *this;
}
};
注意: