c++中运算符重载
时间: 2025-06-10 19:45:01 浏览: 21
### C++ 运算符重载的使用方法及示例
#### 1. 运算符重载类型
C++ 支持对多种运算符进行重载,包括但不限于算术运算符、关系运算符、赋值运算符、下标运算符等。通过重载这些运算符,可以使用户自定义的数据类型(如类)支持类似于内置类型的自然操作[^1]。
#### 2. 算术运算符重载
算术运算符(如 `+`、`-`、`*`、`/`)可以通过成员函数或友元函数进行重载。以下是一个通过成员函数重载 `+` 运算符的示例:
```cpp
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 重载 + 运算符
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
void display() const {
std::cout << real << " + " << imag << "i" << std::endl;
}
};
int main() {
Complex c1(3, 4), c2(5, 6), c3;
c3 = c1 + c2; // 调用重载的 + 运算符
c3.display(); // 输出结果为 8 + 10i
return 0;
}
```
#### 3. 关系运算符重载
关系运算符(如 `<`、`>`、`==`、`!=`)可以用于比较两个对象。以下是一个通过成员函数重载 `==` 运算符的示例:
```cpp
class Point {
private:
int x, y;
public:
Point(int a = 0, int b = 0) : x(a), y(b) {}
// 重载 == 运算符
bool operator==(const Point& other) const {
return (x == other.x && y == other.y);
}
void display() const {
std::cout << "(" << x << ", " << y << ")" << std::endl;
}
};
int main() {
Point p1(3, 4), p2(3, 4);
if (p1 == p2) { // 调用重载的 == 运算符
std::cout << "Points are equal." << std::endl;
} else {
std::cout << "Points are not equal." << std::endl;
}
return 0;
}
```
#### 4. 下标运算符重载
下标运算符 `[]` 可以用于访问数组元素或容器中的元素。以下是一个通过成员函数重载 `[]` 运算符的示例:
```cpp
class MyArray {
private:
int* data;
int size;
public:
MyArray(int s) : size(s) {
data = new int[size];
for (int i = 0; i < size; ++i) {
data[i] = 0;
}
}
~MyArray() {
delete[] data;
}
// 重载 [] 运算符
int& operator[](int index) {
if (index < 0 || index >= size) {
throw std::out_of_range("Index out of range.");
}
return data[index];
}
int getSize() const {
return size;
}
};
int main() {
MyArray arr(5);
try {
for (int i = 0; i < arr.getSize(); ++i) {
arr[i] = i * 10; // 调用重载的 [] 运算符
}
for (int i = 0; i < arr.getSize(); ++i) {
std::cout << arr[i] << " "; // 输出结果为 0 10 20 30 40
}
} catch (const std::out_of_range& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
```
#### 5. 赋值运算符重载
赋值运算符 `=` 的重载通常用于实现深拷贝,避免浅拷贝导致的问题。以下是一个通过成员函数重载 `=` 运算符的示例:
```cpp
class String {
private:
char* str;
public:
String(const char* s = "") {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
~String() {
delete[] str;
}
// 重载 = 运算符
String& operator=(const String& other) {
if (this != &other) { // 防止自我赋值
delete[] str; // 释放原有资源
str = new char[strlen(other.str) + 1];
strcpy(str, other.str);
}
return *this;
}
void display() const {
std::cout << str << std::endl;
}
};
int main() {
String s1("Hello");
String s2("World");
s2 = s1; // 调用重载的 = 运算符
s2.display(); // 输出结果为 Hello
return 0;
}
```
#### 注意点
- 某些运算符不能被重载,例如 `.`、`.*`、`::` 和 `sizeof`。
- 重载运算符时需注意保持其语义的一致性,避免引起混淆。
- 对于涉及动态内存分配的类,重载赋值运算符时需要特别小心,以避免内存泄漏或双重释放等问题[^1]。
阅读全文
相关推荐



















