您的位置:首页 > 编程语言 > C语言/C++

c++ 类中重写赋值操作符遇到的问题

2015-08-16 15:36 357 查看
c++工程目录结构:



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中进行两个对象的+(重写后的),会出现结果无法正常返回的现象:



原因是:


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: