重載運算符
來源:程序員人生 發布時間:2015-06-16 08:40:49 閱讀次數:3100次
假設我們有以下結構體聲明:struct CarType
{
string maker;
int year;
float price;
};
假定我們將mycar聲明為該結構的1個對象,并且為該對象的所有數據成員賦值,然后我們編寫下面的代碼:
if(mycar>2000)
cout<<"My car is more than 2000"<<endl;
C++不知道如何處理這段代碼,C++其實不知道是將myCar中的year與2000比較還是myCar中的price與2000比較。我們必須通過編寫1個C++能夠履行的函數,告知C++如何處理這1情況。
在C++中,2元運算符通常在左側有1個操作數,右側有1個操作數,為了編寫重載運算符,兩個操作數必須有1個是對象,由于重載運算符函數只能為對象編寫,而且必須為作用于對象的運算符編寫重載運算符函數。如果運算符左側的操作數是結構的對象,那末全部函數定義通常位于結構定義的內部,然后運算符右側的操作數作為參數傳遞給函數。
struct CarType
{
string maker;
int year;
float price;
//重載操作符 >
bool operator >(float number)
{
if(price>number)
return true;
return false;
}
};
一樣可以像下述代碼調用函數1樣:
mycar.operator>(2000)
如果CarType mycar ,yourcar;
if(myCar>yourcar)編譯器會報錯,由于yourcar不能傳遞給參數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;
}
};
現在我們定義了兩個運算符>函數,調用哪個函數取決于右操作數的類型,C++將試圖進行匹配,如果沒法匹配,編譯器將會報錯.
如果我們編寫以下代碼:if(2000 < mycar)
cout<<"My car is more than 2000"<<endl;
當左操作數不是對象,而右操作數是對象時,最好將函數定義直接放在結構定義的下面.
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;
}
//結構和類之間的差別:1結構關鍵詞struct 類關鍵詞class 2.結構中默許公有,類中默許私有.
int main()
{
CarType mycar,yourcar;
mycar.maker="Mercedes";
mycar.year=2014;
mycar.price=45567.7155;
//屬于同1個結構的對象之間能進行對象賦值
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版權所有.本站文章除注明出處外,皆為作者原創文章,可自由援用,但請注明來源.
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈