运算符重载
非常实用.
1.必须为已经定义的运算符.
2.不能改变优先级.
3."=" ,"()" ," []" ,"?: " 四个只能用成员函数实现...
4.不能重载的...如下: "," ".*" "::" "*" "#" "sizeof"
实例1:
// 运算符重载.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class CComplex
{
private:
double re,im;
public:
CComplex(double r,double i);
CComplex operator+(CComplex &rhs);
friend CComplex operator-(CComplex &,CComplex &);
void printself();
};
CComplex::CComplex(double r,double i)
{
re = r;
im = i;
}
CComplex CComplex::operator+(CComplex & rhs)
{
return CComplex(re + rhs.re,im + rhs.im);
}
void CComplex::printself()
{
if(im > 0)
cout << re <<"+" << im << "i" << endl;
else
cout << re << im << "i" <<endl;
}
CComplex operator-(CComplex &lhs,CComplex & rhs)
{
CComplex a(0,0);
a.re = lhs.re - rhs.re;
a.im = lhs.im - rhs.im;
return a;
}
int _tmain(int argc, _TCHAR* argv[])
{
CComplex c1(1,2);
CComplex c2(3,-4);
CComplex c3 = c1 + c2;
CComplex c4 = c1 - c2;
c1.printself();
c2.printself();
c3.printself();
c4.printself();
getchar();
return 0;
}
实例2:
// ++overload.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
int i;
A operator++();
// A operator++(int );
};
A A::operator ++()
{
cout<<"call ++A"<<endl;
i++;
return *this;
}
/*A A::operator ++(int)
{
cout<<"call A++"<<endl;
i++;
return *this;
}
*/
int _tmain(int argc, _TCHAR* argv[])
{
A a;
a.i = 4;
++a;
a++;
cout<<a.i<<endl;
getchar();
return 0;
}