【问题标题】:define static function outside the class and access static value .h and .cc files在类外定义静态函数并访问静态值 .h 和 .cc 文件
【发布时间】:2011-12-16 01:17:27
【问题描述】:
 //foo.h
 class Foo 
  {
    private:
      static int number;

    public: 
      static int bar();
  };

//foo.cc
#include "foo.h"

 int Foo::bar() 
 {
   return Foo::number;
 }

这不起作用。我想在类定义之外定义一个静态函数并访问一个静态值。

undefined reference to `Foo::number'

【问题讨论】:

  • 从未定义静态值。在 foo.cc 中添加int Foo::number;

标签: c++ class static


【解决方案1】:

你必须定义Foo::number:

// foo.cc
...
int Foo::number(0);

【讨论】:

    【解决方案2】:

    您刚刚声明了需要定义它的静态成员。 将此添加到您的 cpp 文件中。

    int Foo::number = 0;
    

    这应该是一本好书:

    what is the difference between a definition and a declaration?

    【讨论】:

    • 谢谢!当将 Foo::number 设置为私有时,我不知道这是可能的
    【解决方案3】:

    你已经声明了 Foo::number 你必须添加一个定义。在你的 cpp 文件中添加这一行

    int Foo::number = 0;  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多