主要还是练习封装,做一个demo。下一步会实现string类。
# include <iostream>
using namespace std;
class my_complex {
private:
int real;
int imag;
public:
my_complex();
my_complex(int real, int imag);
~my_complex();
my_complex(const my_complex& rhs);
my_complex& operator=(const my_complex& rhs);
my_complex& operator+(const my_complex& rhs);
bool operator==(const my_complex& rhs);
friend ostream &operator<<(ostream& output, const my_complex &rhs);
};
my_complex::my_complex() :
real(0), imag(0) {
}
my_complex::my_complex(int real, int imag) :
real(real), imag(imag) {
}
my_complex::my_complex(const my_complex& rhs) {
real = rhs.real;
imag = rhs.imag;
}
my_complex& my_complex::operator +(const my_complex& rhs) {
real = rhs.real + real;
imag = rhs.imag + imag;

本文介绍了使用C++实现复数类的实践,重点在于封装和重载运算符。在实现过程中特别关注了赋值函数的自我赋值问题。经过测试,得到了预期结果。
最低0.47元/天 解锁文章
592

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



