hi, how to declare static data memeber of a class and how to define it?

class Hop {
protected:
  static struct NStrct{
    int nCount;
  }
}

how to implement it? for example if the static member is "static const count", you would declare the static member in implementation file like "int Hop::NStrct::nCount=0;"

Recommended Answers

All 4 Replies

I think you're missing two semicolons:

#include <iostream>

class Hop
{
protected:
  static struct NStrct
  {
    int nCount;
  } test;
};

int main()
{

  return 0;
}

Here are a few cases with explanation to make it clear what they are:

class Hop {
  public: //could be any scope
    //this defines a nested class/struct inside Hop, this is a _type_ (not data member).
    struct NStrct{
      int nCount;
    };
    //the above nested type can be used to defined data members:
    NStrct d1; //this is a data member (non-static) of type Hop::NStrct
    static NStrct d2; //this is a static data member of type Hop::NStrct
    //this defines a data-member and a nested class/struct:
    static struct NStrct2 {
      int nCount;
    } d3; //d3 is a static data member of type Hop::NStrct2.
    NStrct2 d4; //this is a non-static data member of type Hop::NStrct2.
    //you can also define static const data members:
    static const int d5 = 42; //since "int" is a built-in type, you can initialize d5 in the class declaration.
    static const std::string d6; //since std::string is a class, d6 has to be initialized outside of the class declaration.
};

//in the cpp file:
const std::string Hop::d6 = "Hello World";

int main() {
  Hop obj; //declares an object of type Hop.
  //The non-static data members are accessed with an object:
  obj.d1; obj.d4;
  //The static data member are accessed with the class:
  Hop::d2; Hop::d3;
  Hop::d5; Hop::d6;
  //nested types are also accessed via the class:
  Hop::NStrct v1;
  Hop::NStrct2 v2;

  return 0;
};

I worked it out and here is the answer:

//header file 

class Test{
protected:
	static int _nCount;
	struct Garbade{
		int _nCount;
		Garbade():_nCount(20){}
	}static _garbage;
public:
	Test(){++_nCount;}
	static int getCount(){return _nCount;}
	static int getGarbage(){return _garbage._nCount;} 
};
#include "static.h"
#include <iostream>
int Test::_nCount=0;
Test::Garbade Test::_garbage;
int main(){
	Test test1,test2,test3;
	std::cout<<test1.getCount()<<std::endl;
	std::cout<<test1.getGarbage()<<std::endl;
	std::cin.get();
	return 0;
}

The thing is static class members need to be allocated separatelly from a class, because all static members are shared amoung objects, so you need declare it in implamentation file and initialization will take place with a constructor help;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.