1. 程式人生 > >c++ 類中重寫賦值操作符遇到的問題

c++ 類中重寫賦值操作符遇到的問題

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中進行兩個物件的+(重寫後的),會出現結果無法正常返回的現象:

原因是: