简体   繁体   中英

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:

/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; 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.

In your case, you need to add

int A::cnt=0; // = 0 Would be better, otherwise you're accessing an uninitialized variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM