当谈到 C++ 中的 “operator”(运算符)时,通常指的是运算符重载(operator overloading)。运算符重载允许用户重新定义或扩展内置运算符的操作行为,使其适用于自定义的类型或类对象。通过运算符重载,可以为自定义类型定义与内置类型相似的语义和操作。
运算符重载的一般语法如下:
return_type operator op (parameters) {
// 运算符重载的实现
}
其中,operator
是关键字,用于表示运算符重载。op
是要重载的运算符,可以是任何合法的 C++ 运算符。return_type
是运算符重载函数的返回类型,表示操作的结果类型。parameters
是传递给运算符重载函数的参数。
下面是一些常见的运算符重载示例:
- 算术运算符重载:
class Vector {
public:
int x, y;
Vector operator+(const Vector& other) const {
Vector result;
result.x = x + other.x;
result.y = y + other.y;
return result;
}
};
Vector v1 = {1, 2};
Vector v2 = {3, 4};
Vector sum = v1 + v2; // 重载了加法运算符,实现向量相加
- 关系运算符重载:
class Point {
public:
int x, y;
bool operator==(const Point& other) const {
return (x == other.x) && (y == other.y);
}
};
Point p1 = {1, 2};
Point p2 = {1, 2};
bool isEqual = (p1 == p2); // 重载了相等运算符,判断两个点是否相等
- 输入/输出运算符重载:
#include <iostream>
class Complex {
public:
double real, imag;
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
};
Complex c = {2.5, 1.3};
std::cout << c; // 重载了输出运算符,以自定义格式打印复数
- 赋值运算符重载:
class MyClass {
public:
int value;
MyClass& operator=(const MyClass& other) {
value = other.value;
return *this;
}
};
MyClass obj1;
MyClass obj2;
obj2.value = 42;
obj1 = obj2; // 重载了赋值运算符,实现对象之间的成员变量赋值
这些示例说明了运算符重载的一些用法,通过重载运算符,可以使自定义类型的对象支持原生运算符,从而提供更直观和灵活的操作方式。运算符重载可以简化代码,提高代码的可读性和可维护性。但需要注意,运算符重载应该按照一定的规则和语义进行设计,以避免混淆和不当的使用。