阅读量:2
在C++中,运算符重载是一种允许你自定义已有运算符行为的方法
#include
using namespace std;
class Complex {
public:
Complex(double real = 0, double imag = 0) : real_(real), imag_(imag) {}
// 重载加法运算符
Complex operator+(const Complex& other) const {
return Complex(real_ + other.real_, imag_ + other.imag_);
}
// 重载输出运算符
friend ostream& operator<<(ostream& os, const Complex& c) {
os << "(" << c.real_ << ", " << c.imag_ << ")";
return os;
}
private:
double real_;
double imag_;
};
int main() {
Complex c1(3, 4);
Complex c2(1, 2);
Complex c3 = c1 + c2;
cout << "c1 + c2 = " << c3 << endl;
return 0;
}
在这个例子中,我们定义了一个名为Complex的类,它表示复数。我们重载了加法运算符(operator+)以允许两个复数相加。同时,我们还重载了输出运算符(operator<<),以便在输出复数时提供更友好的格式。
在main函数中,我们创建了两个复数对象c1和c2,并将它们相加得到一个新的复数对象c3。然后我们使用重载的输出运算符将c3打印出来。
以上就是关于“c++实现运算符重载”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm