使用构造函数来比较/计算用户输入

Using Constructors to compare/calc user input

本文关键字:计算 用户 输入 比较 构造函数      更新时间:2023-10-16

在我的程序中,我应该接受2个money值(创建2个类/构造函数实例),但我也应该比较它们。我不知道如何比较它们,也不知道该使用哪个构造函数(我有3个重载构造函数)。第一个被注释掉的if语句是我对比较值的看法,但它一直在重新打印displayMoney()与我写它的次数相同。第二个if语句是关于我认为程序将如何根据用户输入选择要使用的构造函数。很抱歉,使用构造函数/oveloading是个新手,它会让人困惑。

这是我到目前为止的代码:

#include <iostream>
#include <string>
using namespace std;
class money
{
private:
    int dollars;
    int cents;
public:
    money();
    money(int str);
    money(int str1, int str2);
    double displayMoney();
};
money::money()
{
    dollars = 0;
    cents = 0;
}
money::money(int str)
{
    dollars = str;
    cents = 0;
}
money::money(int str1, int str2)
{
    dollars = str1;
    cents = str2;
}
double money::displayMoney()
{
   double total = dollars + cents/(double)100;
   cout << "$" << total << endl;
   return total;
}


int main()
{
    int input11, input12, input21, input22;
    money c;
    cout << "Enter 2 money values: "<< endl;
    cout << "n Dollars 1: ";
    cin >> input11;
    cout << " Cents 1: ";
    cin >> input12;
    cout << "n Dollars 2: ";
    cin >> input21;
    cout << " Cents 2: ";
    cin >> input22;
    money x(input11, input12);
    money y(input21, input22);
  /*if(x.displayMoney() > y.displayMoney())
   {
        cout << "n $" << x.displayMoney() << " is greater than " << "$" <<    y.displayMoney() << endl;
   }
   else if(x.displayMoney() < y.displayMoney())
   {
        cout << "n $" << y.displayMoney() << " is greater than " << "$" << x.displayMoney() << endl;
   }
   else
   {
       cout << "n $" << x.displayMoney() << " is equal to " << "$" << y.displayMoney() << endl;
   }*/

 /*if (input1 > 0 && input2 > 0)
   {
       money x(input1, input2);
       x.displayMoney();
   }
   else if (input2 <= 0 && input1 > 0)
   {
       money x(input1);
       x.displayMoney();
   }
   else
   {
       money x;
       x.displayMoney();
   }*/
   return 0;
 }

您有两个选择。重载一个或多个比较运算符,或者提供一个返回单个可比较值(总美分)的方法。

选项1:

class money {
  //...
  public:
    bool operator< ( const money & b ) const {
        return dollars < b.dollars || dollars == b.dollars && cents < b.cents;
    }
};

您可以用类似的方式定义operator>operator==,也可以从operator<:派生它们

bool operator> ( const money & a, const money & b ) { return b < a; }
bool operator== ( const money & a, const money & b ) { return !(a < b || b < a); }

选项2:

class money {
  //...
  public:
      int totalCents() const { return dollars * 100 + cents; }
};

现在,您可以在没有运算符重载的情况下比较实际金额,因为您已经将"货币"减少为一个内置值。