Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Please answer this c++ static question!?

This program won't compile correctly

// Bell.h file

#ifndef BELL_H

#define BELL_H

class Bell

{

private:

int count1;

static int count2;

public:

Bell()

{ count1 = 0; }

void ring(int);

int getCount() const

{ return count1; }

static int getStaticCount() const

{ return count2; }

};

#endif

//specification of ring function and main function (Bell.cpp)

#include <iostream>

#include "Bell.h"

using namespace std;

void Bell::ring(int num_rings)

{

for (int index = 0; index < num_rings; index++)

{

cout << "ring ";

count1++;

count2++;

}

}

int main()

{

const int NUM_RINGS1 = 3, NUM_RINGS2 = 4;

Bell bell1, bell2;

bell1.ring(NUM_RINGS1);

bell2.ring(NUM_RINGS2);

cout << "Count for first bell: " << bell1.getCount();

cout << "Count for second bell: " << bell2.getCount();

cout << "Static Counter: " << bell1.getStaticCount();

system("pause");

return 0;

}

Basically bell1 should ring 3 times and bell2 should ring 4 times

and should print out the count for each bell and the static counter,

which is the same for both.

Please help me? I'm not so good with programming

1 Answer

Relevance
  • 7 years ago

    This is in response to your email contact. I did show you exactly what to type. Just before Bell::ring, add:

    int Bell::count2 = 0;

    Don't put that inside of a function, and don't use "static" on this line. That's what a static member variable definition looks like...an ordinary global variable, but with classname:: in front of the variable name to show that it's a static member that's being defined.

    It can go in any .cpp file in your project, by the way, but it has to be in one place and one place only. That's why you do NOT put static variable definitions in the .h file...because that definition would then show up in every .cpp file that included the header. (No harm here, with only one .cpp file, but bad practice in general.)

Still have questions? Get your answers by asking now.