重载算术运算符c ++

时间:2015-02-25 01:45:57

标签: c++ operators overloading

我刚刚开始学习C ++课程,而且我在处理重载算术运算符时遇到了一些问题。首先,在我的头文件中,我有:

#ifndef MONEY_H
#define MONEY_H
#include <iostream>
using namespace std;

class Money{
    public:
        Money(int dollars, int cents);
        Money(int dollars);
        Money();
        int getDollars() const {return dollars;};
        int getCents() const {return cents;};
        void setDollarsAndCents(int dollars, int cents);
        double getAmount() const {return amount ;};
        void setAmount(double amount);

        // Define operator functions  for comparison operators
        friend bool operator==(const Money& firstAmount, const Money& secondAmount);
        friend bool operator<(const Money& firstAmount, const Money& secondAmount);
        friend bool operator>(const Money& firstAmount, const Money& secondAmount);

        //Define operator functions for arithmetic operators
        friend Money operator+(const Money& firstAmount, const Money& secondAmount);
        friend Money operator-(const Money& firstAmount, const Money& secondAmount);
        friend Money operator*(const Money& money, int n);
        friend Money operator/(const Money& money, int n);

        //Define the output and input operator
        friend ostream& operator<<(ostream& outStream, const Money& money);
    private:
        int dollars, cents;
        double amount;
};
#endif

然后我在一个实现文件Money.cpp

上实现了operator +
  #include "Money.h"

// Construct a money object with dollars and cents
Money::Money(int newDollars, int newCents)
{
    dollars = newDollars;
    cents = newCents;
}
// Construct a money object with JUST the dollars
Money::Money(int newDollars)
{
    dollars = newDollars;
    cents = 0;
}
// Construct a money object with no arguments (default amount = 0)
Money::Money()
{
    amount = 0.0;
}
// Set dollars and cents
void Money::setDollarsAndCents(int newDollars, int newCents)
{
    dollars = newDollars;
    cents = newCents;
}
// Set monetary amount
void Money::setAmount(double newAmount)
{
    //convert cents automatically if >= 100
    newAmount = dollars + cents/100.0;
    amount = newAmount;
}
// Test if two Money objects are equal or not
bool operator==(const Money& firstAmount, const Money& secondAmount)
{   
    return (firstAmount.amount == secondAmount.amount);
}
// Test if the first operand is less than the second operand
bool operator<(const Money& firstAmount, const Money& secondAmount)
{
    return (firstAmount.amount < secondAmount.amount);
}
// Test if the first operand is greater than the second operand
bool operator>(const Money& firstAmount, const Money& secondAmount) 
{
    return (firstAmount.amount > secondAmount.amount);
}
// Add two Money objects
Money operator+(const Money& firstAmount, const Money& secondAmount)
{
    //assume cents < 100
    int carry = 0;
    int finalCents = firstAmount.cents + secondAmount.cents;

    if (finalCents >= 100){
        carry += 1;
        finalCents -= 100;
    }
    int finalDollars = firstAmount.dollars + secondAmount.dollars + carry;

    return Money(finalDollars, finalCents);
}
// Subtract two Money objects
Money operator-(const Money& firstAmount, const Money& secondAmount)
{
    int borrow = 0;
    int finalCents = firstAmount.cents - secondAmount.cents;
    if (finalCents < 0){
        finalCents += 100;
        borrow = 1;
    }
    int finalDollars = firstAmount.dollars - secondAmount.dollars - borrow;
    return Money(finalDollars, finalCents);
}
// Multiply two Money objects
Money operator*(const Money& money, int n)
{
    return money.amount * n;
}
// Divide two Money objects
Money operator/(const Money& money, int n)
{
    int quotient = money.amount / n;
    // check if there isn't a remainder
    if ( quotient * n == 0)
        return money.amount / n;
    else // there's a remainder
        return money.dollars / n + money.cents / (n * 100);
}
// Define the output operator
ostream& operator<<(ostream& outputStream, const Money& money)
{
    outputStream << money.amount;
   return outputStream;
}

最后,在我的TestMoney.cpp的主要方法中,我有:

#include "Money.h"
using namespace std;

int main()
{
    Money m1(-35),m2(53, 35);

    //Test operator == (false)
    cout << "m1 == m2 = " << (m1 == m2 ? "true" : "false")  << endl;

    Money m3(-35),m4(35); 

    //Test operator < (true)
    cout << "m3 < m4 = " << (m3 < m4 ? "true" : "false")  << endl;

    Money m5(-35),m6(53, 35); 

    //Test operator > (false)
    cout << "m5 > 6 = " << (m5 > m6 ? "true" : "false")  << endl;

    Money m7(12,50),m8(25,55); 
    // $12.50 & $25.50 = $38.05
    //Test operator +
    cout << "m7 + m8 = $" << (m7 + m8) << endl;

    //~ Money m9(5,75), m10(100); 
    //~ // $5.75 - $100 = $-94.25
    //~ //Test operator -
    //~ cout << "m9 - m10 = $" << m9 - m10 << endl;

    //~ Money m11(25,75);
    //~ int n = 5;
    //~ // $25.75 * $5 = $128.75
    //~ //Test operator *
    //~ cout << "m11 * m12 = $" << m11 * n << endl;

    //~ Money m13(115,75);
    //~ n = 3;
    //~ // $115.75 / $3 = $38.58333
    //~ //Test operator /
    //~ cout << "m13 / n = $" << m13 / n << endl;
    return 0;

}

显然,我得到答案:m7 + m8 = $4.94066e-324。答案应该是38.05美元。

我已经被困在这里很长一段时间了。如果有人能够耐心地解释我搞砸了哪里会很棒。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

在这种情况下,您使用的构造函数重载不会设置&#39; amount&#39;。

Money::Money(int newDollars, int newCents)
{
    dollars = newDollars;
    cents = newCents;
}

你的operator+

也不是
Money operator+(const Money& firstAmount, const Money& secondAmount)
{
    //assume cents < 100
    int carry = 0;
    int finalCents = firstAmount.cents + secondAmount.cents;

    if (finalCents >= 100){
        carry += 1;
        finalCents -= 100;
    }
    int finalDollars = firstAmount.dollars + secondAmount.dollars + carry;

    return Money(finalDollars, finalCents);
}

您的operator<<显示amount且未初始化。

您应该在所有构造函数重载中设置amount。这可能是通过让它们都调用一个在一个地方执行init的私有函数来实现的。

更好地摆脱了以2种表示形式存储价值的双重性(美元/美分和金额)。只能将它存储为一个或另一个,它将变得更加简单。

另请注意,如果您调用no args构造函数,则您的美元和美分成员变量同样未初始化。

答案 1 :(得分:0)

问题是您的operator <<输出amount成员。然而,它是未初始化的:

// Define the output operator
ostream& operator<<(ostream& outputStream, const Money& money)
{
    outputStream << money.amount;  // not initialized
    return outputStream;
}

如果您查看cout中的main,就可以了:

(m7 + m8)

这会返回一个临时的Money对象,它将被复制构造(不是默认构造的)。复制构造函数是编译器生成的(可以,但请参阅下面的评论)。由于m7m8已设置amount,因此您将垃圾值复制到临时Money对象,从而将垃圾值复制。


此外,由于double变量amount未初始化,您的代码调用未定义的行为,并且编译器生成的复制构造函数将垃圾双值复制到另一个double。除非操作涉及初始化变量,否则您永远不想尝试操作未初始化的浮点变量。

最重要的是,在构建对象时,您应该努力将所有成员初始化为已定义的状态。它是否使指针为NULL,是否使双精度等于0等等。您的成员变量应设置为有效状态。