类的操作符重载 :关键字operator再加上需要被重载的操作符,如下代码实现将两个Emploee类的对象进行相加。
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
using std::string;
class Emploee
{
public:
Emploee(string name,int age);
Emploee();
~Emploee();
Emploee operator+(const Emploee& temp)
{
Emploee result;
result.m_sname = this->m_sname + temp.m_sname;
result.m_nage = this->m_nage + temp.m_nage;
return result;
}
int getEmploeeage();
string getEmploeename();
private:
string m_sname;
int m_nage;
};
Emploee::Emploee(string name,int age)
{
m_sname = name;
m_nage = age;
}
Emploee::Emploee()
{
}
Emploee::~Emploee()
{
}
int Emploee::getEmploeeage()
{
return m_nage;
}
string Emploee::getEmploeename()
{
return m_sname;
}
int main()
{
Emploee *yuan = new Emploee("yuan",10);
Emploee *song = new Emploee("song",12);
Emploee result;
result = *yuan + *song;
cout << result.getEmploeeage() << "\n" << result.getEmploeename() << endl;
delete(yuan);
delete(song);
}