1. 创建complex复数类
#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
using namespace std;
class complex
{
public:
complex(int re = 0, int im = 0)
{
real = re;
image = im;
}
//重载负号
complex operator -()
{
return complex(-real, -image);
}
//重载减号
friend complex operator -(const complex &c1, const complex &c2)
{
return complex(c1.real-c2.real, c1.image-c2.image);
}
friend ostream &operator <<(ostream &os, const complex &c)
{
os << "(" << c.real << ", " << c.image << ")";
return os;
}
private:
int real;
int image;
};
#endif // COMPLEX_H
2. 测试代码
complex c1(3,3);
complex c2(5,5);
cout << -c1 << endl;
cout << c2 -c1 <<endl;
3. 运行结果
4. 参考文献:
1) C++面向对象高级开发
2) C++同时重载减号运算符和负号运算符的问题
本文介绍了一个简单的C++复数类的实现,并演示了如何重载负号和减号运算符来支持复数的算术操作。通过具体的代码示例和运行结果展示了复数对象的创建、取反以及两个复数相减的过程。

9426

被折叠的 条评论
为什么被折叠?



