- 运算符重载定义时可以看做是函数
class Yunsuan
{ public:
Yunsuan operator+(Yunsuan&);//此处即将运算符看作是函数
//参数为对象
}
#include "Yunsuan.h"
//以上为自己定义的类头文件
//以下为在cpp文件中定义的运算符重载
Yunsuan Yunsuan::operator+(Yunsuan & other)//对象参数名为other
{
Yunsaun result(this->m_value + other.m_value);
//这里加号重载之后就可以直接实现两个对象的私有成员相加,
//传给第三个对象
return result;//返回一个对象
}
接下来在主函数中运行:
#include <iostream>
#include "Yunsuan.h"
using namespace std;
void TestYunsuan();
int main()
{
TestYunsuan();//在主函数中调用TestYunsuan()函数
}
void TestYunsuan()
{ Yunsuan int1(1024),int2(2048),int3;
int3 = int1 + int2;//这里int1作为this指向的对象
//而int2就是传入的other对象,两者相加即m_value私有成员相加
cout << "int3中m_value的值为:" << int3.GetValue() << endl;
}
2.可以将输入输出流重载,这样在输出和输入对象中的私有变量时不用调用函数,可直接输出。
- 重载输出运算符<<
#include <include>
using namespace std;//使ostream合法化
class Yunsuan
{ public:
ostream & operator<<(ostream &,Yunsuan &);//在类中声明
}
#include "Yunsuan.h"
#include <iostream>
using namespace std;
//ostream不用域操作
ostream & operator<<(ostream & out,Yunsuan & another)
{ out << another.m_value;
return out;
}
在主函数中的调用
int main()
{ Yunsuan int3(128);
cout << "int3中m_value的值为:" << int3 <<endl;
//这里的输出直接输出int3即对象名就可输出对象中的私有成员的值
}
2.重载输入运算符>>
#include <iostream>
using namespace std;
class Yunsuan
{ public:
istream & operator>>(istream & ,Yunsuan &);
}
#include <iostream>
#include "Yunsuan.h"
using namespace std;
//同样istream不用引用域运算符
istream & operator>>(istream & in, Yunsuan & another)
{ cout << "请输入m_value的值:";
in >> another.m_value;
return in;
}
//在主函数的调用
int main()
{ Yunsuan int4;
cin >> int4;//从键盘输入一个值给int4.m_value
//测试是否成功赋值
cout << "int4中m_value的值为:" << int4 << endl;
//若输出运算符已经重载,则直接输出int4即可测试
}