c++加法运算符重载
时间: 2023-12-22 13:28:10 浏览: 95
下面是C++中加法运算符重载的例子:
```cpp
#include <iostream>
using namespace std;
class Complex {
private:
double real, imag;
public:
Complex() :real(0), imag(0) {} // 无参构造函数
Complex(double r, double i) :real(r), imag(i) {} // 用参数初始化表对其数据成员初始化
Complex operator+(const Complex& c) const { // 重载加法运算符
return Complex(real + c.real, imag + c.imag);
}
friend ostream& operator<<(ostream& o, const Complex& c); // 友元函数,重载输出运算符
friend istream& operator>>(istream& is, Complex& c); // 友元函数,重载输入运算符
};
ostream& operator<<(ostream& o, const Complex& c) { // 重载输出运算符
o << c.real << "+" << c.imag << "i";
return o;
}
istream& operator>>(istream& is, Complex& c) { // 重载输入运算符
is >> c.real >> c.imag;
return is;
}
int main() {
Complex c1(1.2, 3.4), c2(5.6, 7.8);
Complex c3 = c1 + c2; // 调用重载的加法运算符
cout << c1 << " + " << c2 << " = " << c3 << endl; // 调用重载的输出运算符
cin >> c1; // 调用重载的输入运算符
cout << "c1 = " << c1 << endl; // 调用重载的输出运算符
return 0;
}
```
阅读全文