[英]c++ - Count number of instantiations of a class
我有一个简单的C ++示例,其中我试图计算一个类的实例数。 我将其基于一个旧的Java示例,并且感到困惑,为什么它不起作用。 我仅尝试访问类的static
成员,但编译失败。
为什么我的默认构造函数会导致编译错误,并尝试创建一个返回静态成员变量的“静态”函数?
我实际上是在尝试在一个类中创建一个可以像全局函数一样调用的函数,而不像传统的C函数那样在类外部声明它。
谢谢。
代码清单
#include <iostream>
using namespace std;
class MyClass {
public:
static int iMyInt;
static int getMyInt();
};
MyClass::MyClass() {
this.iMyInt = 0;
}
static int MyClass::getMyInt() {
return iMyInt;
}
int main(void) {
int someInt = MyClass::getMyInt();
cout << "My Int " << someInt << endl;
return 0;
}
样本输出-构建
test.cpp:10:18: error: definition of implicitly-declared 'MyClass::MyClass()'
MyClass::MyClass() {
^
test.cpp:14:30: error: cannot declare member function 'static int MyClass::getMyInt()' to have static linkage [-fpermissive]
static int MyClass::getMyInt() {
^
编辑
这是我在这里和这里使用建议后的最终(工作)代码清单:
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass();
static int iMyInt;
static int getMyInt();
};
int MyClass::iMyInt = 0;
MyClass::MyClass() {
//this.iMyInt = 0;
cout << "I am a new class" << endl;
}
int MyClass::getMyInt() {
return iMyInt;
}
int main(void) {
MyClass* someClass = new MyClass();
int someInt = MyClass::getMyInt();
cout << "My Int " << someInt << endl;
return 0;
}
样例代码:
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass()
{
instances++;
showInstanceCount();
}
virtual ~MyClass()
{
instances--;
showInstanceCount();
}
static int getInstanceCount()
{
return instances;
}
static void showInstanceCount()
{
cout << "MyClass instance count: " << instances << endl;
}
static int instances;
};
int MyClass::instances = 0;
int main()
{
{ MyClass a, b, c; }
return 0;
}
示例代码的输出 :
MyClass instance count: 1
MyClass instance count: 2
MyClass instance count: 3
MyClass instance count: 2
MyClass instance count: 1
MyClass instance count: 0
静态方法无权访问this
因为它们对现有类的对象不了解。 更改
this.iMyInt = 0
至
MyClass::iMyInt++; //if you want to count number of instances. It's not necessery to zeroing static variables. They are initiated by 0.
对于第一个错误,您尚未在类中声明构造函数。 您必须在类中声明构造函数。
class MyClass {
public:
MyClass(); // Declare the consructor
static int iMyInt;
static int getMyInt();
};
对于第二个问题,在定义函数时不要包含static关键字。 所以,代替
static int MyClass::getMyInt() {
return iMyInt;
}
更改为
int MyClass::getMyInt() {
return iMyInt;
}
最后,除了声明它之外,还需要定义iMyInt
静态数据成员:
int MyClass::iMyInt = 0;
注意这里也没有static
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.