标签:重载运算符
假如我们有如下结构体声明: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++如何处理这一情况。
struct CarType { string maker; int year; float price; //重载操作符 > bool operator >(float number) { if(price>number) return true; return false; } };
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; }
原文链接:http://www.52coder.net/archives/2446.html版权所有.本站文章除注明出处外,皆为作者原创文章,可自由引用,但请注明来源.
标签:重载运算符
原文地址:http://blog.csdn.net/persever/article/details/45417735