문제

I need this program to create a new HotDogStand object that is able to track how many hot dogs are sold by each stand individually and all together, and I cannot figure out how to make my static method work to find the total number of hot dogs sold between all stands. Can someone point me in the right direction please?

#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;
}
도움이 되었습니까?

해결책

Globally (outside of the class), you have to define the static variable:

int HotDogStand::totalSold = 0;

Change

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

And

int HotDogStand::getTotalSold()
{
    return totalSold;   // just return value
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top