读书人

C++小品:重载操作符其实小弟我

发布时间: 2012-09-23 10:28:11 作者: rapoo

C++小品:重载操作符——其实,我是一个成员函数
想起周星驰在《喜剧之王》中的那句:其实,我是一个演员。

操作符重载,其本质上就是类的一个成员函数调用,只是操作符使用起来更加方便自然。例如,
我们的Father类重载了+号,它的实质是一个成员函数,只是这个成员函数的名字有些特别,是一个符号而已,重载+之后,我们就可以这样使用这个重载的操作符:
Father father;
Mother mother;
Baby baby = father +mother; // 这条语句的实质,是以mother为参数调用Father类的+成员函数,相当于
Faby baby = father.+(mother); 看到没有,这个普通成员函数调用并不太大区别,只是因为函数名是一个符号,可以简化我们的代码。
我这样解释你清楚了没有?给我一个回复哦。
From: tao_mail@sina.cn
Sent: Monday, August 15, 2011 10:23 AM
To: 陈良乔


class Mother
{
public:
Mother(string strName):m_strName(strName){}
private:
string m_strName;
};

class Baby
{
public:
string getname()
{
return m_strName;
}
Baby(string strName):m_strName(strName){}
private:
string m_strName;
};

class Father
{
public:
Baby operator+(const Mother& mom)
{
return Baby("chenxibei");
}
};

Mr.Chen,我还是不太懂操作符重载,红色的部分到底是什么意思?是给Baby初始化了?我在主函数中调用getname函数也不是,在主函数中应该怎么用?



[解决办法]
讲故事 ?

读书人网 >C++

热点推荐