需要帮助理解 friend 命令以及如何让我的主要 == 工作
Need help understanding the friend command as well as how to get the == in my main to work
class Cspinner
{
friend ostream & operator <<(ostream & leftside, Cspinner rightside);
private:
int randomSpin;
string FruitName;
int apple;
int orange;
int cherry;
int banana;
int peach;
int fruit;
public:
Cspinner()
{
randomSpin = 0;
srand(time(NULL));
apple = 30;
orange = 25;
cherry = 20;
banana = 15;
peach = 10;
}
Cspinner(int newapple, int neworange, int newcherry, int newbanana, int newpeach)
{
randomSpin = (rand() % 100) + 1;
apple = newapple;
orange = neworange;
cherry = newcherry;
banana = newbanana;
peach = newpeach;
srand(time(NULL));
}
void spin()
{
randomSpin = (rand() % 100) + 1;
if (randomSpin <= peach)
{
FruitName = "peach ";
}
else if (randomSpin <= (peach + banana))
{
FruitName = "banana ";
}
else if (randomSpin <= (peach + banana + cherry))
{
FruitName = "cherry ";
}
else if (randomSpin <= (peach + banana + cherry + orange))
{
FruitName = "orange ";
}
else if (randomSpin <= (peach + banana + cherry + orange + apple))
{
FruitName = "apple ";
}
}
};
ostream & operator <<(ostream & leftside, Cspinner rightside)
{
leftside << rightside;
return leftside;
}
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;
}
}
本质上,我在这里创建了老虎机的开头,但是我对 friend 命令不太熟悉。我也无法弄清楚如何让朋友在程序的主运行中使用 ==。我将如何将两者联系起来并让 w1(w2, w3( 基本上理解主弦,以便我可以看到是否所有的轮子/旋转器都相互排列?
任何帮助将不胜感激,我不想要代码本身,我想了解我做错了什么以及如何与朋友联系。
要让==
在main
函数中工作,您需要执行两件事:
- 更改
main
的返回类型 - 为类实现
operator==
。
main
函数始终向操作系统返回int
。 您可以返回EXIT_SUCCESS
或EXIT_FAILURE
。
实现类的==
下面是operator==
方法的模具:
bool operator==(const Mspinner& other) const
{
bool is_equal = true;
if (this != &other)
{
// Compare your data fields, for example:
is_equal = FruitName == other.FruitName;
is_equal = is_equal && (apple == other.apple);
//...
}
return is_equal;
}
相关文章:
- 为什么我的 std::ref 无法按预期工作?
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 我的评分程序无法正常工作
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 编译在我的 Mac 上工作,但在集群 (Linux) 上不起作用
- 如何使实例化在我的 OpenGL 程序中工作?
- 我的文件无法正常工作,无法从C++文件中读取上下文
- 我的代码无法正常工作。谁能指出错误?
- 我的 SDL2 程序需要哪些二进制文件,以便它在另一台未安装 SDL2 的计算机中工作
- 代码在 CodeSignal 中工作不正确。不确定这是否是我的代码缺陷
- cout 在我的程序上无法正常工作,有人可以帮助我吗?
- 为什么我的 while 循环对于特定输入中断,而对于其他输入工作正常?
- 为什么我的模运算符无法正常工作?
- 我无法让我的程序工作,我一直得到未定义的符号:C
- VS为我提供了对构造函数的另一个解决方案,但我想知道为什么我的工作不起作用
- 程序在我的C++工作区中找不到头文件
- 在我的工作目录中使用 glfw -3.2.1,如何使用 makefile 使用它进行编译
- 如何在不保存文件的情况下制作打印屏幕并将其发送到FTP服务器?我的工作代码将文件保存到HDD
- 为什么我的工作人员线程未收到此信号
- 错误在我的c++工作