尘世中迷途小书童

假如我们有如下结构体声明:struct CarType{string maker;int year;float price;};

假定我们将mycar声明为该结构的一个对象,并且为该对象的所有数据成员赋值,,然后我们编写下面的代码:

if(mycar>2000)cout<<"My car is more than 2000"<<endl;C++不知道如何处理这段代码,C++并不知道是将myCar中的year与2000比较还是myCar中的price与2000比较。我们必须通过编写一个C++能够执行的函数,告诉C++如何处理这一情况。在C++中,二元运算符通常在左边有一个操作数,右边有一个操作数,为了编写重载运算符,两个操作数必须有一个是对象,因为重载运算符函数只能为对象编写,而且必须为作用于对象的运算符编写重载运算符函数。如果运算符左边的操作数是结构的对象,那么整个函数定义通常位于结构定义的内部,然后运算符右边的操作数作为参数传递给函数。

struct CarType{string maker;int year;float price;//重载操作符 >bool operator >(float number){if(price>number)return true;return false;}};同样可以像下述代码调用函数一样:mycar.operator>(2000)如果CarType mycar ,yourcar;if(myCar>yourcar)编译器会报错,因为yourcar不能传递给参数number,它不是一个整型类型,我们可以编写如下代码:

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;//属于同一个结构的对象之间能进行对象赋值yourcar=mycar;yourcar.price=10000;cout<<"Your car is a:"<<mycar.maker<<endl;cout<<fixed<<showpoint<<setprecision(2)<<"I will offer $"<<mycar.price-200<<" 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;}

原文链接:版权所有.本站文章除注明出处外,皆为作者原创文章,可自由引用,但请注明来源.

只有一条路不能选择——那就是放弃的路;

尘世中迷途小书童

相关文章:

你感兴趣的文章:

标签云: