【问题标题】:C++ - Multi-Classes and Private Data MembersC++ - 多类和私有数据成员
【发布时间】:2015-05-06 16:38:05
【问题描述】:

我正在为我的大学做 C++ 工作,我的代码基于 2 个类, NumSetGame。 数据成员是私有的。

class NumSet
{
    int arr[5];     //Cards
    int Score;
}

class Game 
{
    NumSet P1, P2;              //Player 1 , And Player 2 
    int OpenCard;               //For The Card in The center
}

用于从Game 内部的方法向 P1 \ P2 添加分数 我创建了这个方法:

void NumSet::Addscore()
{
    ++this->Score;
}

还有这个方法:

void NumSet::PrintScore()
{
    cout << this->Score << endl;
}

到目前为止,一切看起来都很好,但出于某种原因 当我调用Addscore方法时:

P2.Addscore();

它将其值从 0 提高到 2..

NumSet::NumSet()        //C'tor
{
    for (int i = 0; i < STARTCARDS; i++)
        arr[i] = NULL;
    this->Sort();       //BubbleSort
    Score = 0;
}

void Game::ChangeCards()
{
    if (x1 > x2)        //Player 1 is Stronger
        P1.Addscore();

    else if (x2 > x1)   //Player 2 is Stronger
        P2.Addscore();

    else                //Both Cards Are Equal
    {               //Checkin For The Lower Max Num
        int max1 = P1.Max();     //Max returns maximum num in arr
        int max2 = P2.Max();
        if (max1 < max2)
            P1.Addscore();
        else if (max2 < max1)
            P2.Addscore();
    }
}

我真的很想解释一下这里出了什么问题。

谢谢!

【问题讨论】:

  • 您能否为您的代码创建一个minimal compilable sample,以重现您描述的行为?
  • @WillBriggs 嘿,谢谢你的回复,你说的所有东西都是无关紧要的,因为这些东西已经在代码中声明了,但我没有把它复制到这里..
  • @user1978011 抱歉,我想我可以得到一些帮助来整理和理解,代码本身要大得多,我完成了 90% 的工作,我只是想要 P2.addscore 的帮助..
  • 评论不用于扩展讨论;这个对话是moved to chat
  • 这是我在尝试编译时得到的错误,当然这是可以预测的:Cannot open include file: 'NumSet.h': No such file or directory

标签: c++ class constructor


【解决方案1】:

这里似乎没有什么问题......只要确保 - 1) 分数初始化为 0 2) 不做任何错误的赋值或递增

【讨论】:

  • @unix14 “上传的完整代码 –” 你没有,你链接了它,这比你原来的帖子还要糟糕。如上所述,请创建一个MCVE
猜你喜欢
  • 2011-06-18
  • 2016-09-10
  • 2011-02-24
  • 2010-09-17
  • 1970-01-01
  • 2019-12-29
  • 2014-03-12
  • 2011-07-30
  • 1970-01-01
相关资源
最近更新 更多