使用构造函数来比较/计算用户输入
Using Constructors to compare/calc user input
在我的程序中,我应该接受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; }
};
现在,您可以在没有运算符重载的情况下比较实际金额,因为您已经将"货币"减少为一个内置值。
相关文章:
- C++如何计算用户输入的数字中的偶数位数
- 函数计算用户按下按钮的频率
- 如何计算字符串中用户输入元素的出现次数?
- 用于在C++中计算用户数据的线程
- 检查用户是否是 Windows 中本地计算机上的管理员C++
- 如何在 C++ 中使用 if-then 语句正确计算用户输入
- 我需要制作一个程序来计算用户输入的特定数量的数字
- 计算用户使用循环输入的整数数量
- 计算当前日期和用户输入日期问题之间的天数
- 使用用户定义的类来计算某些类似的类模板
- 如果用户要求重复程序,我该如何清除以前计算的数据?C
- 基于用户输入(C 学校项目)计算
- 如何从用户那里获得输入字符串而不是示例,然后计算空格、标点符号、数字和字母.C++
- 从用户输入中计算可能的最少可能的硬币
- 在计算使用了多少个数组索引的同时,如何填充一个来自用户输入的字符的数组?(使用cin.get)
- 如何用3个用户定义的函数计算一个数字的真平方根
- 在用户计算机上存储密钥的推荐方法
- 使用构造函数来比较/计算用户输入
- 如何制作一个计数器来计算用户输入的奇数和偶数的个数?
- 如何计算用户输入列表的最大值、最小值和平均值