4.重載雙目運算符
class String
{
public:
String(){ p = NULL; } //定義默認構造函數
String(char* str); //聲明構造函數
friend bool operator > (String &string1, String &string2);//聲明運算符函數爲友元函數
void display();
private:
char *p; //字符型指針,用於指向字符串
};
String::String(char* str)
{ p = str; }
void String::display()
{ cout << p; }
bool operator > (String &string1, String &string2)
{
if (strcmp(string1.p,string2.p) > 0)
{
return true;
}
else
{
return false;
}
}
Void compare(String &string1, String &string2)
{
if(operator >(string1,string2) > 0)
{
String1.display(); cout<<”>”; String2.display();
}
}
int main()
{
String string1("hello"), string2("Book");
compare(string1, string2);
return 0;
}
5.重載單目運算符
單目運算符(!a,-b,&c,*p,++i,–i等)只有一個操作數,因此運算符重載函數只有一個參數,如果運算符重載函數作爲成員函數,則還可省略此參數。
例子:
class Time
{
public:
Time(){ min = 0; sec = 0; }
Time(int m,int s) : min(m),sec(s){}
Time operator ++ ();
void display(){ cout << min << ":" << sec; }
private:
int min;
int sec;
};
Time Time::operator++()
{
if (++sec >= 60)
{
sec -= 60;
++min;
}
return *this; //返回當前對象值
}
int main()
{
Time time1(34, 0);
for (int i = 0; i < 61;i++)
{
++time1; //運算符的操作數是一個對象,而且與運算符函數的類型相同
time1.display();
}
return 0;
}
問題:前置自增運算符和後置自增運算符,他們的作用是不一樣的,在重載時怎麼區分?
C++約定:在自增(自減)運算符重載函數中,增加一個int型形參,就是後置自增(自減)運算符函數。
如:
Time operator ++ (); //聲明前置自增運算符“++”重載函數
Time operator ++ (int); //聲明後置自增運算符“++”重載函數
例子:
class Time
{
public:
Time(){ min = 0; sec = 0; }
Time(int m, int s) : min(m), sec(s){}
Time operator ++ (); //聲明前置自增運算符++重載函數
Time operator ++ (int); //聲明後置自增運算符++重載函數
void display(){ cout << min << ":" << sec; }
private:
int min;
int sec;
};
Time Time::operator++()//前置自增運算符++重載函數
{
if (++sec >= 60)
{
sec -= 60;
++min;
}
return *this; //返回的是自加後的對象
}
Time Time::operator++(int) //後置自增運算符++重載函數
{
Time temp(*this);
sec++;
if (sec >= 60)
{
sec -= 60;
++min;
}
return temp; //返回的是自加前的對象
}
int main()
{
Time time1(34, 59),time2;
time1.display(); //34:59
++time1;
time1.display(); //35:0
time2 = time1++; //將自加前的對象的值賦值給time2
time1.display(); //35:1
time2.display(); //35:0
return 0;
}