简体   繁体   English

在访问类的静态成员时遇到麻烦

[英]trouble in accessing static members of a class

Have a look at the following code: 看下面的代码:

//abc.h //abc.h

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

//abc.cpp //abc.cpp

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

//main.cpp //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(). 好的,您有一个abc类,它具有一个静态成员a和一个函数init()。 What you do not have in your program (in main in your example) is any actual instances of class abc. 您程序中没有的内容(在示例中主要是)是abc类的所有实际实例。 Because of this: 因为这:

a. 一种。 there is no instance of abc upon which init() can be called. 没有abc实例可以在其上调用init()。

b. 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. 链接器不会在最终程序中包含abc :: a-我认为您永远不会获得静态成员变量,除非您在某处至少有一个相关对象。

So at the least you should add: 因此,至少您应该添加:

abc g_abc;
g_abc.init();

inside main() before the cout. 在cout之前的main()内部。

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. 另外,正如Mat所说,您需要将abc.cpp链接到您的项目中,否则程序中没有abc :: a或abc :: init()。

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. 您可能需要考虑一个在创建abc对象时便对其进行初始化的构造函数,但是如果该构造函数唯一能做的就是设置a的值,那可能就不是您想要的,因为每次您都会重置a制作一个新的abc。 You could change the line "int abc::a;" 您可以更改“ int abc :: a;”行 in abc.cpp to "int abc::a = 0;" 在abc.cpp中为“ int abc :: a = 0;” so that a is initialised when the program starts. 以便在程序启动时初始化a。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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