重載運算符
來源:程序員人生 發(fā)布時間:2015-06-16 08:40:49 閱讀次數(shù):3104次
假設(shè)我們有以下結(jié)構(gòu)體聲明:struct CarType
{
string maker;
int year;
float price;
};
假定我們將mycar聲明為該結(jié)構(gòu)的1個對象,并且為該對象的所有數(shù)據(jù)成員賦值,然后我們編寫下面的代碼:
if(mycar>2000)
cout<<"My car is more than 2000"<<endl;
C++不知道如何處理這段代碼,C++其實不知道是將myCar中的year與2000比較還是myCar中的price與2000比較。我們必須通過編寫1個C++能夠履行的函數(shù),告知C++如何處理這1情況。
在C++中,2元運算符通常在左側(cè)有1個操作數(shù),右側(cè)有1個操作數(shù),為了編寫重載運算符,兩個操作數(shù)必須有1個是對象,由于重載運算符函數(shù)只能為對象編寫,而且必須為作用于對象的運算符編寫重載運算符函數(shù)。如果運算符左側(cè)的操作數(shù)是結(jié)構(gòu)的對象,那末全部函數(shù)定義通常位于結(jié)構(gòu)定義的內(nèi)部,然后運算符右側(cè)的操作數(shù)作為參數(shù)傳遞給函數(shù)。
struct CarType
{
string maker;
int year;
float price;
//重載操作符 >
bool operator >(float number)
{
if(price>number)
return true;
return false;
}
};
一樣可以像下述代碼調(diào)用函數(shù)1樣:
mycar.operator>(2000)
如果CarType mycar ,yourcar;
if(myCar>yourcar)編譯器會報錯,由于yourcar不能傳遞給參數(shù)number,它不是1個整型類型,我們可以編寫以下代碼:
struct CarType
{
string maker;
int year;
float price;
//重載操作符 >
bool operator >(float number)
{
if(price>number)
return true;
return false;
}
bool operator >(CarType yourcar)
{
if(price>yourcar.price)
return true;
return false;
}
};
現(xiàn)在我們定義了兩個運算符>函數(shù),調(diào)用哪個函數(shù)取決于右操作數(shù)的類型,C++將試圖進行匹配,如果沒法匹配,編譯器將會報錯.
如果我們編寫以下代碼:if(2000 < mycar)
cout<<"My car is more than 2000"<<endl;
當左操作數(shù)不是對象,而右操作數(shù)是對象時,最好將函數(shù)定義直接放在結(jié)構(gòu)定義的下面.
struct CarType
{
string maker;
int year;
float price;
//重載操作符 >
bool operator >(float number)
{
if(price>number)
return true;
return false;
}
bool operator >(CarType yourcar)
{
if(price>yourcar.price)
return true;
return false;
}
};
bool operator <(int number ,CarType car)
{
if(car.price > number)
return true;
return false;
}
完全代碼以下:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct CarType
{
string maker;
int year;
float price;
//重載操作符 >
bool operator >(float number)
{
if(price>number)
return true;
return false;
}
bool operator >(CarType yourcar)
{
if(price>yourcar.price)
return true;
return false;
}
};
bool operator <(int number ,CarType car)
{
if(car.price > number)
return true;
return false;
}
//結(jié)構(gòu)和類之間的差別:1結(jié)構(gòu)關(guān)鍵詞struct 類關(guān)鍵詞class 2.結(jié)構(gòu)中默許公有,類中默許私有.
int main()
{
CarType mycar,yourcar;
mycar.maker="Mercedes";
mycar.year=2014;
mycar.price=45567.7155;
//屬于同1個結(jié)構(gòu)的對象之間能進行對象賦值
yourcar=mycar;
yourcar.price=10000;
cout<<"Your car is a:"<<mycar.maker<<endl;
cout<<fixed<<showpoint<<setprecision(2)<<"I will offer $"<<mycar.price⑵00<<" for your car"<<endl;
if(mycar>2000)
cout<<"My car is more than 2000"<<endl;
if(mycar>yourcar)
cout<<"My car is worth more than your car"<<endl;
if(2000 < mycar)
cout<<"My car is more than 2000"<<endl;
mycar.operator>(2000);;
mycar.operator>(yourcar);
operator<(2000,mycar);
return 0;
}
原文鏈接:http://www.52coder.net/archives/2446.html版權(quán)所有.本站文章除注明出處外,皆為作者原創(chuàng)文章,可自由援用,但請注明來源.
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進行捐贈