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;
}
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:
public
fields in classes, so I turned a
into private
,If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With