[英]C++ static functions and variables
I have written a class as shown below: 我写了一个课,如下所示:
#include<iostream>
using namespace std;
class A
{
static int cnt;
static void inc()
{
cnt++;
}
int a;
public:
A(){ inc(); }
};
int main()
{
A d;
return 0;
}
I want to call the function inc through the constructor, but when i compile i am getting an error as: 我想通过构造函数调用函数inc,但是当我编译时,出现如下错误:
/tmp/ccWR1moH.o: In function `A::inc()':
s.cpp:(.text._ZN1A3incEv[A::inc()]+0x6): undefined reference to `A::cnt'
s.cpp:(.text._ZN1A3incEv[A::inc()]+0xf): undefined reference to `A::cnt'
I am unable to understand what the error is... plz help... 我无法理解错误是什么...请帮助...
Static field is not defined - Take a look at Why are classes with static data members getting linker errors? 静态字段没有定义-看看为什么有静态数据成员得到了链接错误类? .
。
#include<iostream>
using namespace std;
class A
{
static int cnt;
static void inc(){
cnt++;
}
int a;
public:
A(){ inc(); }
};
int A::cnt; //<---- HERE
int main()
{
A d;
return 0;
}
Inside the class static int cnt;
里面的类
static int cnt;
is only declared, and need to be defined. 仅声明,并且需要定义。 In C++ you usually declare in your .h .hpp files and then define your static class members in your .c and .cpp files.
在C ++中,通常在.h .hpp文件中声明,然后在.c和.cpp文件中定义静态类成员。
In your case, you need to add 对于您的情况,您需要添加
int A::cnt=0; // = 0 Would be better, otherwise you're accessing an uninitialized variable.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.