8. 重载操作符实例:
1)输出操作符<<重载 (注意:IO操作符必须为非成员函数)
#include<iostream>
using namespace std;
class CTest
{
public:
CTest(int m, float f):a(m),f(f){}
friend ostream& operator<<(ostream& out,const CTest& obj); //作为友元
private:
int a;
float f;
};
.cpp文件中:
ostream& operator<<(ostream& out,const CTest& obj)
{
out<<obj.a<<"\t"<<obj.f;
return out; //方便调用时多次输出
}
int main()
{
CTest test(5, 5.5);
operator<<(operator<<(cout, test),test); //输出两次。调用方式一。 直接使用cout
cout << test << test; //输出两次。调用方式二 。 直接使用cout
system("pause");
return 0;
}
2) 输入操作符>>重载
#include<iostream>
using namespace std;
class CTest
{
public:
friend istream& operator>>(istream& ii, CTest& obj);
public:
int a;
float f;
};
.cpp中
istream& operator>>(istream& ii, CTest& obj)
{
ii >> obj.a; //输入值放入obj.a中
return ii;
}
int main()
{
CTest test;
cin >> test >> test; //可以多次输入
cout<<test.a<<endl;
system("pause");
return 0;
}
3) 加法操作
作为非成员函数时:
#include<iostream>
using namespace std;
class CTest
{
public:
CTest(){}
CTest(int m, float f):a(m),f(f){}
friend CTest operator+(CTest& obj1, CTest& obj2);
public:
int a;
float f;
};
.cpp中:
CTest operator+(CTest& obj1, CTest& obj2)
{
int b = obj1.a + obj2.a;
float f = obj1.f + obj2.f;
CTest test(b, f);
return test; //返回后是值拷贝。可以的。
}
//CTest& operator+(CTest& obj1, CTest& obj2)
//{
// int b = obj1.a + obj2.a;
// float f = obj1.f + obj2.f;
// CTest test(b, f);
// return test; //返回引用是错误的,因为退出函数后,栈空间释放。去掉&是值拷贝,正确方式
//}
int _tmain(int argc, _TCHAR* argv[])
{
CTest test1(1, 1.1);
CTest test2(2, 2.2);
CTest test3;
test3 = operator+(test1, test2); //调用方式一
test3 = test1 + test2; //调用方式二
cout<<test3.a<<endl;
cout<<test3.f<<endl;
system("pause");
return 0;
}
作为成员函数时:
#include<iostream>
using namespace std;
class CTest
{
public:
CTest(){}
CTest(int m, float f):a(m),f(f){}
CTest operator+(CTest& obj);
public:
int a;
float f;
};
.cpp中:
CTest CTest::operator+(CTest& obj)
{
int b = this->a + obj.a;
float f = this->f + obj.f;
CTest test(b, f);
return test;
}
int _tmain(int argc, _TCHAR* argv[])
{
CTest test1(1, 1.1);
CTest test2(2, 2.2);
CTest test3;
test3 = test1.operator +(test2); //作为成员函数的调用方式
cout<<test3.a<<endl;
cout<<test3.f<<endl;
system("pause");
return 0;
}
4) 相等判断
作为成员函数时,非成员函数省略。
#include<iostream>
using namespace std;
class CTest
{
public:
CTest(){}
CTest(int m, float f):a(m),f(f){}
bool operator==(CTest& obj);
public:
int a;
float f;
};
bool CTest::operator==(CTest& obj)
{
if (this->a == obj.a)
{
return true;
}
return false;
}
int _tmain(int argc, _TCHAR* argv[])
{
CTest test1(1, 1.1);
CTest test2(1, 2.2);
if (test1.operator ==(test2))
{
cout<<"yes"<<endl;
}
system("pause");
return 0;
}
