C++语言对运算符重载制定了一下规则:绝大部分运算符都能被重载,不能重载的运算符只有一下几个:成员访问运算符'.';成员指针访问运算符'.*';作用域运算符'::';长度运算符'sizeof';条件运算符'?:'。
在C++中,运算符重载可以通过成员函数或非成员函数(通常是友元函数)来实现。是否需要参数列表取决于运算符的类型和它是作为成员函数还是非成员函数来重载的。
一元运算符
一元运算符包括前置和后置自增、自减、取反等。
-
前置运算符:如
++
(前置自增)、--
(前置自减)、-
(取负)、!
(逻辑非)。
作为成员函数重载时,不需要参数。
class MyClass {
public:
MyClass& operator++() { // 前置自增运算符重载为成员函数
// 增加逻辑
return *this;
}
};
- 后置运算符:如
++
(后置自增)、--
(后置自减),需要一个int
类型的哑参数来区分前置和后置。
class MyClass {
public:
MyClass operator++(int) { // 后置自增运算符重载为成员函数
MyClass temp = *this;
// 增加逻辑
return temp;
}
};
二元运算符
二元运算符包括加法、减法、乘法、除法、赋值等。成员函数在重载时会隐含地操作当前对象作为第一个操作数。如 FunNumber operator-(); int operator-(FunNumber);FunNumber operator-(int);
- 作为成员函数重载时,需要一个参数,该参数表示右操作数。
class MyClass { public: MyClass operator+(const MyClass& other) const { // 加法运算符重载为成员函数 MyClass result; // 加法逻辑 return result; } };
示例说明
假设我们有一个类
Complex
,用于表示复数,并希望重载二元运算符。
1. 加法运算符 (+)
class Complex {
public:
double real, imag;
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// 成员函数重载加法运算符
Complex operator+(const Complex& rhs) const {
return Complex(real + rhs.real, imag + rhs.imag);
}
};
-
2. 减法运算符 (
-
)
class Complex {
public:
double real, imag;
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// 成员函数重载减法运算符
Complex operator-(const Complex& rhs) const {
return Complex(real - rhs.real, imag - rhs.imag);
}
};
3.乘法运算符 (*)
class Complex {
public:
double real, imag;
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// 成员函数重载乘法运算符
Complex operator*(const Complex& rhs) const {
return Complex(real * rhs.real - imag * rhs.imag, real * rhs.imag + imag * rhs.real);
}
};
4.除法运算符 (/)
class Complex {
public:
double real, imag;
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// 成员函数重载除法运算符
Complex operator/(const Complex& rhs) const {
double denom = rhs.real * rhs.real + rhs.imag * rhs.imag;
return Complex((real * rhs.real + imag * rhs.imag) / denom, (imag * rhs.real - real * rhs.imag) / denom);
}
};
5.赋值运算符 (=)
class Complex {
public:
double real, imag;
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
// 成员函数重载赋值运算符
Complex& operator=(const Complex& rhs) {
if (this == &rhs) return *this; // 自我赋值检查
real = rhs.real;
imag = rhs.imag;
return *this;
}
};
对于赋值运算符,由于它需要修改左操作数,只能作为成员函数重载。其他二元运算符可以选择成员函数形式或非成员函数形式进行重载。