需要帮助理解 friend 命令以及如何让我的主要 == 工作

Need help understanding the friend command as well as how to get the == in my main to work

本文关键字:我的 工作 助理 帮助 friend 命令      更新时间:2023-10-16
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_SUCCESSEXIT_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;
}