复数类CComplex
大约 3 分钟
复数类CComplex
运算符重载:运算符不仅能实现原有的功能,而且能实现在函数中指定的新的功能。本质还是函数重载或函数多态
//格式
函数类型 operator 运算符名称(形参表) {
对运算符的重载处理
}
operator
是关键字,是专门用于定义重载运算符的函数的,运算符名就是C++已有的运算符。
运算符重载的规则
- C++用户,只能对已有的C++运算符进行重载。
- 只有5个:
.
成员访问运算符.*
成员指针访问运算符::
域运算符sizeof
长度运算符?:
条件运算符
- 重载运算符运算对象(即操作数)的
- 重载不能改变运算符的别
- 重载不能改变运算符的
- 重载不能改变
- 重载的运算符必须,其参数至少有一个是类对象(或类对象的引用)
- 用于类对象的运算符一般必须重载,但有两个例外,“=”和“&”不必用户重载
测试sizeof是运算符
//测试sizeof是运算符
int number = 10;
sizeof(number)
sizeof number//ok
究竟把运算符重载作为类的成员函数好,还是友元函数好?
(1)C++规定,。 (2)和、不能定义为类的成员函数,。 (3)一般将单目运算符和复合运算符( += , -= , /= , = , &= , != , ^= , %= , >>= , <<= )重载为成员函数 。 (4)一般将*重载为友元**函数。
代码实现
#include <iostream>
using namespace std;
class CComplex
{
public:
CComplex(int r = 0, int i = 0)
:_mreal(r)
,_mimage(i)
{
}
void operator=(const CComplex&obj)
{
this->_mreal = obj._mreal;
this->_mimage = obj._mimage;
}
//指导编译器怎么做CComplex类对象的加法操作
/*CComplex operator+(const CComplex&com)
{
return CComplex(this->_mreal + com._mreal,
this->_mimage + com._mimage);
}*/
CComplex operator++(int)
{
return CComplex(this->_mreal++, this->_mimage++);
/*CComplex comp = *this;
this->_mimage++;
this->_mreal++;
return comp;*/
}
CComplex& operator++()
{
_mreal += 1;
_mimage += 1;
return *this;
}
void operator+=(const CComplex&rhs)
{
this->_mreal += rhs._mreal;
this->_mimage += rhs._mimage;
}
void show() { cout << "real:" << _mreal << "image:" << _mimage << endl; }
private:
int _mreal;
int _mimage;
friend CComplex operator+(const CComplex &lhs, const CComplex &rhs);
friend ostream& operator<<(ostream&out, const CComplex&src);
friend istream& operator>>(istream&in, CComplex&src);
};
istream& operator>>(istream&in, CComplex&src)
{
int a, b;
in >> a >> b;
src._mreal = a;
src._mimage = b;
return in;
}
ostream& operator<<(ostream&out, const CComplex&src)
{
out << "real:" << src._mreal << "image:" << src._mimage << endl;
return out;
}
CComplex operator+(const CComplex &lhs, const CComplex &rhs)
{
return CComplex(lhs._mreal + rhs._mreal, lhs._mimage + rhs._mimage);
}
int main()
{
CComplex c1(1, 2);
CComplex c2(2, 3);
CComplex c4;
c4 = c1+c2;
c4.show();
c4 = c1 + 20;
c4.show();
c4 = 30 + c2;
c4.show();
CComplex c5;
c5 = c4++;
c5.show();
c5 = ++c4;
c5.show();
c5 += c4;
c5.show();
cout << "++++++++++++++++++++++++++++++" << endl;
cout << c5;
CComplex c6;
cin >> c6;
cout << c6;
return 0;
}