繁体   English   中英

重载算术运算符c ++

[英]overloading arithmetic operators c++

我刚开始学习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的main方法中,我有:

#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。

我已经在这里停留了一段时间了。 如果有人可以耐心地解释我搞砸的地方,那就太好了。 谢谢您的帮助。

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

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

您的operator+也不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 最好让它们都调用一个在一个地方进行初始化的私有函数来最好地实现。

更好地摆脱了以2种表示形式(美元/美分和金额)存储值的重复性。 仅将其存储为一个或另一个,它将变得更加容易维护。

还要注意,如果调用no args构造函数,则$和cents成员变量同样会被初始化。

问题是您的operator <<输出了amount成员。 但是它尚未初始化:

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

如果你看看你coutmain ,你有这样的:

(m7 + m8)

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


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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM