【问题标题】:static void function linking error静态无效函数链接错误
【发布时间】:2014-03-11 03:40:00
【问题描述】:

我创建了一个小程序,它使用静态 void 函数来获取数字和另一个静态 void 函数来显示数字。但是当应用程序运行时,它会给我这个错误

错误 1 ​​错误 LNK2001: 无法解析的外部符号 "private: static int 事物::i" (?i@Thing@@0HA)

这是我的代码

#include <iostream>
using namespace std;

class Thing{
private:
    static int i;
public:
    static void set_i(int h){
        i = h;
    }
    static void print_i(){
        cout << "The value of i is: " << i << endl;
    }
};

int main(){
    Thing::set_i(25);
    Thing::print_i();
    system("pause");
    return 0;
}

【问题讨论】:

标签: c++ class runtime-error static-members


【解决方案1】:

你应该定义Thing::i 而不是仅仅声明它:

class Thing{
private:
  static int i; // this is only a declaration
  ...
}

int Thing::i = 0; // this is a definition

int main(){
  ...
}

有关声明和定义的区别的更多详细信息,请参阅What is the difference between a definition and a declaration?
这是一个更具体的静态问题:static variable in the class declaration or definition?

【讨论】:

    【解决方案2】:

    需要在类外部定义静态成员。

    static int i; // This is just declaration.
    

    在您的代码中添加以下内容。

    int Thing::i;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 2018-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多