我有一个简单的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() {
^
修改
这是我在使用此处的建议和here后的最终(工作)代码列表:
#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;
}
答案 0 :(得分:3)
You are probably looking for this
示例代码:
#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
答案 1 :(得分:2)
静态方法无权访问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.
答案 2 :(得分:2)
对于第一个错误,您尚未在类中声明构造函数。你必须在类中声明构造函数。
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
。