在C++中,运算符重载允许为用户定义的类型(类或结构体)赋予某些内置运算符的功能。下面是一个关于关系运算符重载(==)和算术运算符重载(+)的简单例子。
示例:复数类的运算符重载
将创建一个表示复数的类,并为其重载==和+运算符。
【cpp】
#include
using namespace std;
class Complex {
private:
double real;
double imag;
public:
// 构造函数
Complex(double r = 0.0, double i = 0.0) : real®, imag(i) {}
// 重载关系运算符 ==
bool operator==(const Complex& other) const {return (real == other.real && imag == other.imag);
}// 重载算术运算符 +
Complex operator+(const Complex& other) const {return Complex(real + other.real, imag + other.imag);
}// 用于打印复数
void print() const {if (imag < 0)cout << real << " - " << -imag << "i" << endl;elsecout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3.0, 4.0);
Complex c2(3.0, 4.0);
Complex c3(1.0, 2.0);
// 使用重载的 == 运算符
if (c1 == c2) {cout << "c1 is equal to c2" << endl;
} else {cout << "c1 is not equal to c2" << endl;
}// 使用重载的 + 运算符
Complex c4 = c1 + c3;
cout << "c1 + c3 = ";
c4.print();return 0;
}
解释
-
复数类定义:
• Complex类有两个私有成员变量:real和imag,分别表示复数的实部和虚部。
• 构造函数允许使用给定的实部和虚部初始化复数对象。
-
关系运算符重载:
【cpp】
bool operator==(const Complex& other) const {
return (real == other.real && imag == other.imag);
}
• 这个重载的==运算符比较两个复数对象的实部和虚部是否相等。
• const关键字表示该函数不会修改调用它的对象。
- 算术运算符重载:
【cpp】
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
• 这个重载的+运算符返回一个新的Complex对象,其实部和虚部分别是两个操作数对应部分的和。
• 同样,const关键字表示该函数不会修改调用它的对象。
-
打印函数:
• print方法用于格式化输出复数,根据虚部的正负决定输出形式。
-
main函数:
• 创建了几个Complex对象,并使用重载的==和+运算符进行比较和加法运算。
• 结果通过cout输出。
这个例子展示了如何在C++中为用户定义的类型重载关系运算符和算术运算符,使这些类型的对象能够像内置类型一样使用这些运算符。