在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;
}
};
注意: