【问题标题】:How to declare extern class pointers in C++?如何在 C++ 中声明外部类指针?
【发布时间】:2015-05-19 17:30:03
【问题描述】:

下面是cpp文件中声明的变量但是报错,所以研究了一下,发现需要在头文件中声明。因此如何在头文件中声明和外部类指针

 extern AnimationController* g_pAnimationController;

【问题讨论】:

  • 就像你做的那样。但是,您首先需要一个前向声明class AnimationController;。 (可以放在源文件中,不使用header,虽然会导致维护问题)

标签: c++ pointers header extern


【解决方案1】:

就像你在那里一样。例如:

// In header file:
// Declare the pointer with external linkage.
extern int* my_global_int;

// In source file:
// Define the pointer so that the linker can link stuff together with the code
// referencing the `my_global_int` symbol.
int* my_global_int = 0;

对于类和结构,如果类型未知,那么我们需要一个前向声明,以便编译器知道它是什么。但我们可以将它与声明结合起来,如下所示:

// In header file:
extern class AnimationController* g_pAnimationController;

或者写得更冗长:

// In header file:
class AnimationController;
extern AnimationController* g_pAnimationController;

评论问题更新:

#include <map>
#include <string>

// Declare AnimationCallback
extern std::map<std::string, AnimationCallback*> g_mCallbackMap;

【讨论】:

  • class std::map &lt;std::string, AnimationCallback*&gt; g_mCallbackMap; 给出错误。我该如何解决它
  • 简单方法:#include 并去掉那个 class 关键字。更难的方法,不推荐:namespace std {template &lt;class Key, class Val, class Pred, class Alloc&gt; class map;},我们仍然需要去掉 class 说明符。
  • 在答案中添加更新。如果您没有,我们还需要声明此AnimationCallback*。编译器必须理解它看到的每个符号,否则就像“AnimationCallback 到底是什么”? “到底是什么std::map”?所以我们必须在基本层面上教它是什么,因此你的前向声明和函数原型等等。我们不必一直教它所有东西,就像我们只需要给它一个函数的原型,而不是头文件中的定义(不是实现它的完整代码),但我们确实需要给它一些想法.
猜你喜欢
  • 2011-01-17
  • 2021-07-08
  • 2010-11-20
  • 1970-01-01
  • 2018-02-27
  • 1970-01-01
  • 2011-09-14
  • 2014-12-01
  • 2021-12-22
相关资源
最近更新 更多