问题
How do I access a static member in a class with all static methods?
I want to have a group of related functions but also have some important data members initialized before any of these functions are called. I thought a class with only static members would be the way to go. Compiler in VS2008 doesn't like me trying to access "a".
Surely I'm missing something small but still very confused. :P (Even without the invalid access of "a" the constructor isn't called when calling testMethod() from main.
class IPAddressResolver
{
private:
public:
static int a;
IPAddressResolver();
static void TestMethod();
};
IPAddressResolver::IPAddressResolver()
{
IPAddressResolver::a = 0;
cout << "Creating IPAddressResolver" << endl;
}
void IPAddressResolver::TestMethod()
{
cout << "testMethod" << endl;
}
回答1:
You need to define your static data member outside of the function, like
class IPAddressResolver
{
private:
static int a;
IPAddressResolver();
public:
static void TestMethod();
};
int IPAddressResolver::a = 0;
void IPAddressResolver::TestMethod()
{
cout << "testMethod" << endl;
}
Your constructor is not called, since you don't create a new instance of the class. For a static utility class, you don't need instances, so you can omit the constructor altogether. Alternatively, you might want to declare it private
to make it explicit that the class shall not be instantiated (see above).
Notes:
- it is not recommended to use
public
fields in classes, so I turneda
intoprivate
, - static utility classes are usually stateless, so if you need to have fields within your class, this maybe a sign that the class would better be a Singleton.
回答2:
Somewhere outside of the class definition, you need to define and initialize your static data members associated with that class.
Easiest is just to put
int IPAddressResolver::a = 0;
in your IPAddressResolver.cpp file.
回答3:
I want to have a group of related functions but also have some important data members initialized before any of these functions are called
Sounds to me like you want a Singleton, not a class with only static members.
来源:https://stackoverflow.com/questions/2992948/static-class-data-members-and-constructors