gpt4 book ai didi

c++ - 热狗摊静态功能问题

转载 作者:行者123 更新时间:2023-11-28 07:01:27 24 4
gpt4 key购买 nike

我需要这个程序来创建一个新的 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
}

关于c++ - 热狗摊静态功能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22419264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com