1.重载双目运算符
未重载版本
#include <iostream>
using namespace std;
class String{
public:
String() { p = NULL; }
String(char *str) { p = str; }
void display() { cout << p<< endl;}
private:
char *p;
};
int main()
{
String str1("Hello"),str2("Book");
str1.display();
str2.display();
return 0;
}
增加友元函数: ' > ' '==' '<' 的尝试
#include <iostream>
#include <cstring>
using namespace std;
class String{
public:
String() { p = NULL; }
String(char *str) { p = str; }
void display() { cout << p;}
friend bool operator >(String &s1,String &s2);
friend bool operator ==(String &s1,String &s2);
friend bool operator <(String &s1,String &s2);
private:
char *p;
};
bool operator >(String &s1, String &s2)
{
if( strcmp( s1.p, s2.p) > 0 )
return true;
return false;
}
bool operator ==(String &s1, String &s2)
{
if( strcmp( s1.p, s2.p) == 0 )
return true;
return false;
}
bool operator <(String &s1, String &s2)
{
if( strcmp( s1.p, s2.p) < 0 )
return true;
return false;
}
void compare(String &s1, String &s2)
{
if(s1 > s2)
{
s1.display() ;
cout << " > " ;
s2.display();
cout << endl;
}
else if(s1 < s2)
{
s1.display() ;
cout << " < " ;
s2.display();
cout << endl;
}
else if(s1 == s2)
{
s1.display() ;
cout << " == " ;
s2.display();
cout << endl;
}
}
int main()
{
String str1("Hello"),str2("book");
str1.display();
str2.display();
compare(str1,str2);
return 0;
}
双目运算符要注意的地方:若作为成员函数,则" 2.5 + c1 "一定是错误的【因为只可能是 " c1 + 2.5 "】。作为友元函数,则要声明和定义两种情况的才能通用。
2.重载单目运算符
常见的单目运算符: !a , -b ,&c , *p 还有 ++,等。单目运算符只有一个操作数,因此运算符只有一个参数,如果运算符重载函数作为成员函数,还可以省略这个参数!
一个例子:【前置++运算符的实现】
#include <iostream>
#include <cstring>
using namespace std;
class Time{
public:
Time(int m = 0, int s = 0) {minute = m; sec = s;}
Time operator++(); //前置"++",由于前置++和后置++的返回值不同,所以需要区分
void display() {cout << minute << " : " << sec << endl;}
private:
int minute,sec;
};
Time Time::operator++()
{
if( ++sec >= 60)
{
sec -= 60;
++ minute;
}
return *this;
}
int main()
{
Time t1(34);
for( int i = 0; i < 61 ; i++)
{
++t1;
//t1++; wrong!!!!
t1.display();
}
return 0;
}
单目运算符常作为成员函数,双目运算符常为友元函数。
如何重载后置++运算符呢?Time operator++(int) ,加上int修饰,虽然int并没有实际作用。
3.重载 " << " 和 " >> " 【流插入、流提取运算符】
返回值是流操作符对象本身。
#include <iostream>
#include <cstring>
using namespace std;
class Complex{
public:
Complex(double r = 0,double i = 0) { real = r; imag = i;}
friend ostream& operator <<
( ostream &, Complex & c);
friend istream& operator >>
( istream &, Complex & c);
Complex operator +(Complex &c)
{return Complex(real + c.real, imag + c.imag);}
private:
double real,imag;
};
/*ostream & operator << (ostream &output, Complex &c)
{
output << "(" << c.real << "+" << c.imag << "i)";
}*/
ostream & operator << (ostream &output, Complex &c)
{
output << "(" <<c.real;
if(c.imag >= 0) output << "+";
output << c.imag << "i)";
return output;
}//修正了当imag为负数时,显示为(4+-10i)的错误
istream & operator >> (istream &input, Complex &c)
{
cout << "please input a compex ...\n";
input >> c.real >> c.imag;
return input;
}
int main()
{
Complex c3;
cin >> c3;
cout << c3 <<endl;
}