#include <iostream>
//#include <vector>
using namespace std;
template<typename T>
class complex {
public:
complex() : re(0), im(0)
{ }
complex(T r, T i)
: re(r) , im(i) // 初值列,初始列
{ }
complex& operator += (const complex<T>&);
// ostream& operator << (ostream& os, const complex& x) {
// return os << "(" << real(x) << "," << imag(x) << ")";
// }
T getReal () const { return re; } // const 表示返回值不会改变内容
// void setReal (T r) { re = r; }
T getImag () const { return im; } // const 表示返回值不会改变内容
// void setImag(T i) { im = i; }
private:
T re, im;
// friend complex<T>& doapl(complex<T>*, const complex<T>&);
};
// 全域函数
template<typename T> // 范型定义
inline T // 返回值定义
getImag(const complex<T>& x) {
return x.getImag();
}
// 全域函数
template<typename T> // 范型定义
inline T // 返回值定义
getReal(const complex<T>& x) {
return x.getReal();
}
// 成员函数的外部定义
// 成员函数的操作符重载外部定义, 该情景下返回值建议使用引用
// 区别在于 已经存在的变量返回引用,函数内部生成的对象不能返回引用.
template<typename T>
inline complex<T>&
complex<T>::operator += (const complex<T>& r){
this->re += r.re;
this->im += r.im;
return *this;
}
//template<typename T>
//inline complex<T>&
//complex<T>::doapl(complex<T>* ths, const complex<T>& x) {
// ths->re += x.re;
// ths->im += x.im;
// return *ths;
//}
// 类外部定义操作符重载
template<typename T>
inline complex<T> // 这里可以返回value, 也可以返回ref
operator + (const complex<T>& x) {
return x;
}
// 类外部定义操作符重载
template<typename T>
inline complex<T> // 这里必须返回value
operator - (const complex<T>& x) {
return complex<T>(-getReal(x), -getImag(x));
}
// 类外部定义操作符重载, 判断两个对象是否相等
template<typename T>
inline bool
operator == (const complex<T>& x, const complex<T>& y) {
return getReal(x) == getReal(y) && getImag(x) == getImag(y);
}
// 类外部定义操作符重载, 判断两个对象是否不相等
template<typename T>
inline bool
operator != (const complex<T>& x, const complex<T>& y) {
return getReal(x) != getReal(y) || getImag(x) != getImag(y);
}
// 打印符号<< 重载.
//#include <iostream>
template<typename T>
ostream&
operator << (ostream& os, const complex<T> x) {
return os << "(" << getReal(x) << ", " << getImag(x) << ")";
}
int main()
{
complex<double> c1(2, 4);
cout << "c1.real: " << c1.getReal() << endl;
cout << "c1.imag: " << c1.getImag() << endl;
complex<double> c2(2, 4);
// 使用成员函数的操作符重载
c2 += c1;
cout << "c1.real: " << c2.getReal() << endl;
cout << "c1.imag: " << c2.getImag() << endl;
// 使用全域函数
cout << "getReal(c2): " << getReal(c2) << " getImag(c2): " << getImag(c2) << endl;
// 使用外部定义的操作符重载
complex<double> c3(33, 44);
complex<double> c4(33, 44);
cout << "(-c3).getReal(): " << (-c3).getReal() << endl;
cout << "(+c4).getReal(): " << (+c4).getReal() << endl;
cout << "c3 == c4: " << (c3 == c4 ) << endl;
cout << "c3 != c4: " << (c3 != c4 ) << endl;
cout << "c3: " << c3 << " c2" << c2 << endl;
return 0;
}
网友评论