热狗站静态功能问题

Hot Dog Stand static function issue

本文关键字:问题 功能 静态 热狗      更新时间:2023-10-16

我需要这个程序来创建一个新的HotDogStand对象,该对象能够跟踪每个摊位单独和所有摊位一起销售了多少热狗,我不知道如何使我的静态方法工作以找到所有摊位之间销售的热狗总数。有人能给我指个正确的方向吗?

#include <iostream>
using namespace std;
class HotDogStand
{
    public:
        HotDogStand(int id, int hds);
        void justSold();
        int getNumSold();
        int getID();
        int getTotalSold();
    private:
        int idNum;
        int hotDogsSold;
    static int totalSold;
};
HotDogStand::HotDogStand(int id, int hds)
{
    idNum = id;
    hotDogsSold = hds;
    return;
}
void HotDogStand::justSold()
{
    hotDogsSold++;
    return;
}
int HotDogStand::getNumSold()
{
    return hotDogsSold;
}
int HotDogStand::getID()
{
    return idNum;
}
int HotDogStand::getTotalSold()
{
    totalSold = 0;
    totalSold += hotDogsSold;
}
int main()
{
    HotDogStand s1(1, 0), s2(2, 0), s3(3, 0);
    s1.justSold();
    s2.justSold();
    s1.justSold();
    cout << "Stand " << s1.getID() << " sold " << s1.getNumSold() << "." << endl;
    cout << "Stand " << s2.getID() << " sold " << s2.getNumSold() << "." << endl;
    cout << "Stand " << s3.getID() << " sold " << s3.getNumSold() << "." << endl;
    cout << "Total sold = " << s1.getTotalSold() << endl;
    cout << endl;
    s3.justSold();
    s1.justSold();
    cout << "Stand " << s1.getID() << " sold " << s1.getNumSold() << "." << endl;
    cout << "Stand " << s2.getID() << " sold " << s2.getNumSold() << "." << endl;
    cout << "Stand " << s3.getID() << " sold " << s3.getNumSold() << "." << endl;
    cout << "Total sold = " << s1.getTotalSold() << endl;
}

全局(在类之外)必须定义静态变量:

int HotDogStand::totalSold = 0;

改变
void HotDogStand::justSold()
{
    hotDogsSold++;
    totalSold++;    // increment here
    return;
}

int HotDogStand::getTotalSold()
{
    return totalSold;   // just return value
}