【问题标题】:Hot Dog Stand static function issueHot Dog Stand 静态功能问题
【发布时间】:2014-03-15 03:45:49
【问题描述】:

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

【问题讨论】:

  • 如果你想知道有多少s1,s2,s3是单独出售的,这种情况下不能使用静态成员。
  • 您遇到了什么错误?
  • 我对单独的总数没有问题,我只是不知道如何找到所有三个热狗摊的总和。 (第一次应该是 3,第二次应该是 5。)@billz
  • 它给了我一个未定义的对 'HotDogStand::totalSold' @HeenaGoyal 的引用
  • 你有几个明显的问题。我希望你不要认为这是无礼的,但我认为你最好复习你的课堂笔记(我假设这是课程作业)。

标签: c++ static static-methods


【解决方案1】:

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

int HotDogStand::totalSold = 0;

改变

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    相关资源
    最近更新 更多