c++ 类中重写赋值操作符遇到的问题
2015-08-16 15:36
357 查看
c++工程目录结构:
currency.h代码如下:
main.cpp代码如下:
运行结果如下:
问题:
如果取消currency.h中赋值操作符的重写函数:
那么在main.cpp中进行两个对象的+(重写后的),会出现结果无法正常返回的现象:
原因是:
currency.h代码如下:
#include <cstdlib> #include <iostream> using namespace std; #ifndef CURRENCY_H #define CURRENCY_H enum Sign{ positive,negative};//plus,minus为C++中的保留字?? class Currency { friend ostream& operator<<(ostream &out,const Currency &c); public: Currency(Sign s=positive,unsigned long dollars=0,unsigned int cents=0); //复制构造函数被用来执行返回值的复制及传值参数的复制。程序中没有给出复制构造函数, //所以C++将使用缺省的复制构造函数,它仅可进行数据成员的复制。 ~Currency() {} // Currency& operator=(const Currency& other)//此赋值操作符的重写实现的功能是? // { // return *this; // } Sign Signature() const { if(amount<0) return negative; return positive; } unsigned long Dollars() const { if(amount<0) return (-amount)/100; return amount/100; } unsigned int Cents() const { if(amount<0) return (-amount)-Dollars()*100; return amount-Dollars()*100; } bool set(Sign s,unsigned long d,unsigned int c); bool set(float a); Currency operator+(const Currency &c) const; Currency& operator+=(const Currency &c) { amount+=c.amount; return *this; } protected: private: long amount; }; Currency::Currency(Sign s,unsigned long d,unsigned int c) { if(c>99) { cerr<<"Cents should be littler than 100"<<endl; exit(-1); } amount=d*100+c; if(s==negative) amount=-amount; } bool Currency::set(Sign s,unsigned long d,unsigned int c) { if(c>99) { cerr<<"Cents should be littler than 100"<<endl; return false; } amount=d*100+c; if(s==negative) amount=-amount; return true; } bool Currency::set(float a) { if(a<0) amount=-((-a)+0.005)*100; else amount=(a+0.005)*100; return true; } Currency Currency::operator+(const Currency &c) const { Currency temp; temp.amount=amount+c.amount; return temp; } ostream& operator<<(ostream &out,const Currency &c) { if(c.amount<0) out<<"-"; out<<"$"; out<<c.Dollars()<<"."; if(c.Cents()<10) out<<"00"<<endl; else out<<c.Cents()<<endl; return out; } #endif // CURRENCY_H
main.cpp代码如下:
#include <iostream> #include "include/currency.h" using namespace std; int main() { Currency g, h(positive, 3, 50), i, j; i.set (-6.45) ; g.set(negative,10,50); j = h + g; cout << "j: "<< j << endl; i += h; cout << "i: "<< i << endl; j = i + g + h; cout << "j: "<< j << endl; j = (i += g) + h; cout << "j: "<< j << endl; cout << "i: "<< i << endl; return 0; }
运行结果如下:
问题:
如果取消currency.h中赋值操作符的重写函数:
Currency& operator=(const Currency& other)//此赋值操作符的重写实现的功能是? { return *this; }
那么在main.cpp中进行两个对象的+(重写后的),会出现结果无法正常返回的现象:
原因是:
相关文章推荐
- (转)为什么宏INT_MIN要写成-2147483647-1
- [LeetCode] Surrounded Regions
- ACM对拍程序
- C++对象模型详解
- C语言 extern学习2 分析
- C++_关于const 的全面总结
- c++的引
- C语言 extern学习1
- C++: 移动构造函数
- 黑马程序员——C语言笔记之if,if....else....,switch判断
- 2015年面试准备(1)-----c/c++的区别
- C++中的结构体和类的异同
- 本科毕设-基于C8051单片机的身份识别系统设计
- java与C语言的数据类型对应
- C语言中运算符优先级
- 自定义多列排序:C++/Java实现
- C语言中个各个进制的表示方法
- C++引用
- C++ Primer 学习笔记与思考_6 数组和动态数组易错点解读
- C++基础---数组