静态类数据成员和构造函数
如何使用所有静态方法访问类中的静态成员?
我想要一组相关的函数,但在调用这些函数之前还需要初始化一些重要的数据成员。我认为只有静态成员的类才是正确的选择。 VS2008 中的编译器不喜欢我尝试访问“a”。
当然,我错过了一些小事,但仍然很困惑。 :P (即使没有“a”的无效访问,当从 main 调用 testMethod() 时,也不会调用构造函数。
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在函数外部定义静态数据成员,例如
您的构造函数不会被调用,因为您没有创建该类的新实例。对于静态实用程序类,您不需要实例,因此可以完全省略构造函数。或者,您可能希望将其声明为
private
,以明确该类不应被实例化(参见上文)。注意:
public
字段,所以我将a
改为private
,You need to define your static data member outside of the function, like
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 turneda
intoprivate
,在类定义之外的某个地方,您需要定义并初始化与该类关联的静态数据成员。
最简单的方法就是放入
IPAddressResolver.cpp 文件。
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
in your IPAddressResolver.cpp file.
我想要一组相关的函数,但在调用这些函数之前还需要初始化一些重要的数据成员
在我看来,您想要一个单例,而不是一个只有静态成员的类。
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.