简体   繁体   中英

trouble in accessing static members of a class

Have a look at the following code:

//abc.h

 class abc{ public: static int a; void init(); }; 

//abc.cpp

#include"abc.h"
  int abc::a;
  void abc::init(){
    abc::a = 10;
  }

//main.cpp

#include<iostream>
#include"abc.h"
   int main(){
  std::cout << abc::a;
  return 0;
 }

Basically What i am trying to achieve is one class writes to a static variable and another class reads from it. Write operation happens before read everytime. I get the following error:

anvith@anvdebian:~/test$ g++ main.cpp
/tmp/ccREguak.o:main.cpp:function main: error: undefined reference to 'abc::a'
collect2: error: ld returned 1 exit status

Kindly help me with what exactly I am doing wrong.

OK, you have a class abc which has a static member a and a function init(). What you do not have in your program (in main in your example) is any actual instances of class abc. Because of this:

a. there is no instance of abc upon which init() can be called.

b. the linker is not going to include abc::a into the final program - I think you never get static member variables unless you have at least one of the relevant object somewhere.

So at the least you should add:

abc g_abc;
g_abc.init();

inside main() before the cout.

Also, as Mat says, you need to link abc.cpp into your project otherwise you don't have abc::a or abc::init() inside the program.

You might want to consider a constructor that initialises an abc object whenever it is created, but if the only thing the constructor can do is to set the value of a, that is probably not what you would want as a will be reset every time you make a new abc. You could change the line "int abc::a;" in abc.cpp to "int abc::a = 0;" so that a is initialised when the program starts.

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