主要还是练习封装,做一个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;
return *this;
}
//需要处理自我赋值(还好,因为这里没有动态内存的分配)
my_complex& my_complex::operator =(const my_complex& lhs) {
real = lhs.real;
imag = lhs.imag;
return *this;
}
bool my_complex::operator ==(const my_complex& rhs) {
return real == rhs.real && imag == rhs.imag;
}
my_complex::~my_complex() {
}
ostream& operator<<(ostream& output, const my_complex &rhs) {
output << rhs.real;
if (rhs.imag > 0) {
std::cout << "+";
}
std::cout << rhs.imag << "i";
return output;
}
int main() {
my_complex c1(1, 5);
my_complex c2(c1); //等价于 my_complex c2 = c1;
my_complex c3(2, 3);
bool flag(c1 == c2);
c1 = c1 + c2;
cout << c1 << endl;
cout << c2 << endl;
cout << c3 << endl;
cout << flag << endl;
}
虽然简单,但是还是有收获,如下:
(1)第一次在程序中有意使用了友元函数,原来用友元函数的好处不少,最直观的一点就是在重载<<的时候,我根本不用提供public的getReal和getImag,因为友元函数对于类内部的访问权限和成员函数一样。
(2)有意识的熟悉了重载运算符
(3)赋值函数一定要注意判断自我赋值
测试结果:
2+10i
1+5i
2+3i
1