很久没有写日记了,今天晚上翻了翻原来学习c++的一些总结,下面运算符重载的一点小知识,对初学者还是有点用的,就贴上来吧!我忘了这个例子是不是我亲自写的了,如有侵权,请多包涵,大家分享知识,呵呵!
当一个类对象和其他类型的数相加的时候,一般会为每一个种情况写一个重载运算符函数,这样很麻烦,我们可以利用构造函数进行隐式的转化。
我们可以利用类构造函数对参与运算的整型对象进行显式的类型转换,从而生成无名对象参与同类型对象的加运算,这样做可以缩减代码量,提高程序的可读性
#include<iostream>
using namespace std;
class RMB
{
public:
RMB(double value);
RMB(unsigned int d, unsigned int c)
{
yuan = d;
jf = c;
while (jf >=100)
{
yuan ++;
jf -= 100;
}
}
// RMB operator + (const RMB& s);
// friend RMB operator + (const RMB& s, double d);
// friend inline RMB operator + (double d, const RMB& s);
friend RMB operator + (const RMB& s1, const RMB& s2);
void display()
{
cout << (yuan + jf / 100.0) << endl;
}
protected:
unsigned int yuan;
unsigned int jf;
};
RMB::RMB(double value)
{
RMB::yuan = value;
RMB::jf = (value - RMB::yuan) * 100.0 + 0.5;
}
/*
RMB RMB::operator + (const RMB& s)
{
unsigned int jf0 = jf + s.jf;
unsigned int yuan0 = yuan + s.yuan;
RMB result(yuan0, jf0);
return result;
}
RMB operator + (const RMB& s, double d)
{
unsigned int y = s.yuan + d;
unsigned int j = s.jf + (d - (int)d) * 100 + 0.5;
RMB result(y, j);
return result;
}
inline RMB operator + (double d, RMB& s)
{
return s + d;
}
*/
RMB operator + (const RMB& s1, const RMB& s2) //这里必须是友员函数
{
unsigned int y = s1.yuan + s2.yuan;
unsigned int j = s1.jf + s2.jf;
RMB result(y, j);
return result;
}
int main()
{
RMB s(5.8);
s = RMB(1.5) + s;
s.display();
s = 1.5 + s;
s.display();
s = s + 1.5; //此处进行隐式转化
s.display();
s = s + 1;
s.display();
s = 4+1.5;//先进行4+1.5的内置double型加法,然后在调用s = RMB(5.5)的隐式转化
s.display();
return 0;
}
类的构造函数起了显式或者隐式转换的作用,转换过程实质是产生一个类的无名对象,类的运算符重载函数的参数就是这个无名对象的引用,所以参数的顺序也不再是问题,代码的运行效率也得到提高,无需再定义只是参数顺序不同,内容重复的运算符重载函数了。
另外,c++中规定: =,(),[],->这四种运算符必须是成员形式。