gpt4 book ai didi

c++ - static void 函数链接错误

转载 作者:搜寻专家 更新时间:2023-10-31 01:05:38 25 4
gpt4 key购买 nike

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

Error 1 error LNK2001: unresolved external symbol "private: static int Thing::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;
}

最佳答案

你应该定义 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?

关于c++ - static void 函数链接错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22315995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com