c++重载运算符
时间: 2025-06-04 09:22:34 浏览: 35
### C++ 中运算符重载的用法和示例
C++ 支持运算符重载,这是一种多态性形式,允许用户定义或修改某些运算符的行为以适用于自定义数据类型。通过运算符重载,可以为类对象提供直观的操作方式[^1]。
#### 运算符重载的基本规则
- 运算符重载不能改变运算符的优先级和结合性。
- 不能创建新的运算符,只能重载现有的运算符。
- 某些运算符(如 `.`、`.*`、`::`、`sizeof`)不能被重载。
- 运算符重载可以通过成员函数或友元函数实现[^2]。
#### 示例代码:重载加法运算符
以下是一个简单的示例,展示如何为一个类重载加法运算符:
```cpp
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 重载加法运算符
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
void display() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3.5, 2.8), c2(1.2, 4.3);
Complex result = c1 + c2; // 使用重载的加法运算符
result.display(); // 输出结果
return 0;
}
```
在上述代码中,`Complex` 类通过成员函数重载了 `+` 运算符,使得两个复数对象可以直接相加[^3]。
#### 示例代码:重载输入输出运算符
重载输入输出运算符(`<<` 和 `>>`)通常需要使用友元函数:
```cpp
#include <iostream>
using namespace std;
class Vector {
private:
double x, y, z;
public:
Vector(double a = 0, double b = 0, double c = 0) : x(a), y(b), z(c) {}
friend ostream& operator<<(ostream& os, const Vector& v); // 输出运算符
friend istream& operator>>(istream& is, Vector& v); // 输入运算符
};
// 实现输出运算符
ostream& operator<<(ostream& os, const Vector& v) {
os << "Vector(" << v.x << ", " << v.y << ", " << v.z << ")";
return os;
}
// 实现输入运算符
istream& operator>>(istream& is, Vector& v) {
is >> v.x >> v.y >> v.z;
return is;
}
int main() {
Vector v;
cout << "Enter vector components: ";
cin >> v; // 使用重载的输入运算符
cout << "You entered: " << v << endl; // 使用重载的输出运算符
return 0;
}
```
在此示例中,`Vector` 类通过友元函数重载了输入和输出运算符,使对象能够方便地与标准流交互[^4]。
### 注意事项
- 当运算符作为成员函数时,左侧操作数必须是该类的对象。
- 如果需要支持左侧操作数为非类类型的运算(如 `int + Complex`),则应使用友元函数[^5]。
阅读全文
相关推荐


















