|
//例子 : /** * 操作符重载*/ #include <iostream> using namespace std; class RMB{ private: unsigned int yuan; //元 unsigned int jf; //角分 public: RMB(double d){ yuan = static_cast<unsigned int> (d); jf = static_cast<unsigned int> ((d-yuan)/100); } RMB interest(double rate);//计算利息 RMB add(RMB d); void display(){ cout << (yuan + jf/100.0)<< endl; } RMB operator+ (RMB d){//人民币+运算符重载 return RMB(yuan + d.yuan + (jf + d.jf)/100); } RMB operator* (double rate){ return RMB( (yuan+jf/100) * rate); } }; RMB RMB::interest(double rate) { return RMB((yuan + jf/100.0) * rate); } RMB RMB::add(RMB d){ return RMB(yuan + d.yuan + jf/100.0+ d.jf/100.0); } RMB expense1(RMB principle , double rate){ RMB interest= principle.interest(rate); return principle.add(interest); } RMB expense2(RMB principle , double rate){ RMB interest = principle * rate; return principle + interest; } int main(){ RMB x =10000.0; double yrate=0.035; expense1(x,yrate).display(); expense2(x,yrate).display(); return 1; } //以上代码在gcc mingw windows环境中编译通过 操作符重载注意事项 : 1 "." , "::" , ".*" , ".->" , "?:" 这5个操作符在c++标准中是不允许重载的,也不可以创造新的操作符 2 操作符在重载后运算优先级保持不变 3 重程序易读性上考虑,操作符重载尽量不要悖弃操作符的本意
|