【发布时间】:2021-05-27 02:12:23
【问题描述】:
为简单起见,这是我的课堂作业:将以下函数添加到 Cspinner 类中。
重载等号以比较两个微调器。如果 w1、w2 和 w3 是微调器,则以下指令应该是有效的。
if ( w1 == w2 && w2 == w3) cout << "You win!";
重载等号以比较微调器和水果(字符数组)。以下指令应该是有效的。
if (w1 == "Apple") cout << "Spinner is a Apple.";
重载输出 (
cout << w1 << endl;
重载类中的一个函数!!
void main()
{
Cspinner w1;
Cspinner w2;
Cspinner w3(80,5,5,5,5);
for (int x=0;x<=9;x++)
{
w1.spin();
w2.spin();
w3.spin();
cout << w1 << " " << w2 << " " << w3;
if (w1 == w2 && w2 == w3)
{
if (w1 == "Apple") cout << " (All Apples) ";
else if (w1== "Orange") cout << " (All Oranges) ";
else if (w1== "Cherry") cout << " (All Cherries) ";
else if (w1== "Banana") cout << " (All Bananas) ";
else cout << " (All Peaches)";
}
cout << endl;
}
}
上述程序的示例输出。
橙苹果苹果 桃 香蕉 苹果 香蕉 苹果 苹果 橙橙苹果 香蕉 樱桃 苹果 橙橙橙(全橙) 橙色 苹果 苹果 桃 苹果 苹果 橘子 苹果 桃子 苹果樱桃苹果
这是我的代码,我只是不知道如何重载运算符,我将不胜感激任何解释这件事。谢谢!
#include <iostream>
using namespace std;
class Cspinner
{
friend void operator << (ostream& left, Cspinner Result);
int apple;
int orange;
int cherry;
int banana;
int peach;
string Result = "Not rolled! ";
public:
Cspinner()
{
apple = 30;
orange = apple + 25;
cherry = orange + 20;
banana = cherry + 15;
peach = banana + 10;
}
Cspinner(int AppleChance, int OrangeChance, int CherryChance, int BananaChance, int PeachChance)
{
apple = AppleChance;
orange = apple + OrangeChance;
cherry = orange + CherryChance;
banana = cherry + BananaChance;
peach = banana + PeachChance;
}
void spin()
{
int RandomNumber = (rand() % 100) + 1;
if (RandomNumber <= apple)
{
Result = "Apple ";
}
else if (RandomNumber <= orange)
{
Result = "Orange ";
}
else if (RandomNumber <= cherry)
{
Result = "Cherry ";
}
else if (RandomNumber <= banana)
{
Result = "Banana ";
}
else if (RandomNumber <= peach)
{
Result = "Peach ";
}
}
bool operator == (char fruit) {
return fruit;
}
bool operator == (Cspinner right) {
return Result == right && left == right;
}
};
//void operator << (ostream left, Cspinner Right) {
// return left, Right;
//}
void main()
{
srand(time(NULL));
Cspinner w1;
Cspinner w2;
Cspinner w3(80, 5, 5, 5, 5);
for (int x = 0;x <= 9;x++)
{
w1.spin();
w2.spin();
w3.spin();
cout << w1 << " " << w2 << " " << w3;
if (w1 == w2 && w2 == w3)
{
if (w1 == "Apple") cout << " (All Apples) ";
else if (w1 == "Orange") cout << " (All Oranges) ";
else if (w1 == "Cherry") cout << " (All Cherries) ";
else if (w1 == "Banana") cout << " (All Bananas) ";
else cout << " (All Peaches)";
}
cout << endl;
}
system("pause");
}
【问题讨论】:
-
不回答,只是请注意,您应该检查总可能性始终为 100。
标签: c++ operators overloading