0

每个人!有如下代码片段: testcase.cpp

#include <string>
#include <iostream>
using namespace std;
class Test {
public:
    static int b ;
    static void test()
    {

        b = 3;
         cout << b<<endl;
    }
};
int main()
{
Test::test();

    return 0;
}

当我单击“构建”按钮时,输出消息是

错误 LNK2001:无法解析的外部符号“public:static int Test::b”(?b@Test@@2HA) 1>B:\PROGRAMPROJECT\visual 2015 pro\testcase\testcase\x64\Debug\testcase.exe:致命错误LNK1120:1 个未解决的外部因素

但是,当我像这样更改代码位置时:

  #include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class Test {
public:
    //static int b;
    static void test()
    {
        static int b;//only change this line
        b = 3;
        cout << b << endl;
    }
};
int main()
{
    Test::test();

    return 0;
}

它确实有效!我不知道为什么?有人可以帮助我吗?我的IDE是vs pro 2015 + windows10。

4

3 回答 3

3

如何解决

使用C++17您可以内联静态变量,从而无需在类外部定义它。

static inline int i = 0; // I would also initialize it to zero, just to be sure 

如果你不能使用C++17你将不得不定义

int Test::b = 0; // Again I would also initialize it to zero, just to be sure 

课外Test

到为什么

当你写

static void test()
{
    static int b; // <-- definition is here
    b = 3;
    cout << b << endl;
}

您直接在类中定义了该函数(这意味着它会自动标记为内联)。然后,您还可以在那里定义静态变量。如果它在函数范围之外,它只是一个声明(除非明确标记为内联 - 如上所示)。

相反,在另一种情况下,它在函数定义之外,因此您缺少静态变量的定义。

class Test {
public:
    static int b ; // <-- only declaration - definition is missing
    static void test()
    {
        b = 3;
        cout << b<<endl;
    }
};

针对 C++17 进行的修复

class Test {
public:
    static inline int b = 0; // <-- now it is defined (and for safety initialized)
    static void test()
    {
        b = 3;
        cout << b<<endl;
    }
};

在 C++17 之前拼写的修复

#include <string>
#include <iostream>
using namespace std;
class Test {
public:
    static int b;   // declaration
    static void test()
    {
        b = 3;
        cout << b << endl;
    }
};

int Test::b = 0;  // definition

int main()
{
    Test::test();

    return 0;
}
于 2018-09-02T09:14:23.897 回答
3

其他答案专注于解决问题,而不是回答“为什么”部分。

当您在类主体中定义一个函数时,它会被自动认为是inline并且任何数量的翻译单元(想想 C++ 源代码)都可以定义它们。这就是你通常在头文件中定义函数的方式——一个函数体将include在多个源中存储。

当你只在类体内声明一个函数,而在外面定义它时,它不会自动标记为inline,这意味着每个包含这个定义的翻译单元都会生成自己的强符号。在这种情况下,您通常将头文件中的声明与关联源文件中的实现分离,否则您会得到多个符号错误。(即,如果您在标头中有非内联定义,则包含它们的每个源都会生成这些符号,并且链接器会感到困惑,因为它看到来自不同来源的同一非内联函数的多个版本)

现在,当您定义静态成员变量时,除非它是内联的,否则它还必须与翻译单元相关联。它类似于声明一个extern全局变量,也必须在某个地方定义。在您的情况下,您应该简单地添加:

int Test::b;

当您将定义与声明分离时,这一点更为重要。说,你有两个文件:

测试.hpp

class Test {
public:
    static int b ;
    static void test();
};

测试.cpp

#include "Test.hpp"
int Test::b;
void Test::test()
{
    b = 3;
    cout << b<<endl;
}

符号(在本例中为全局变量Test::b和函数Test::test)与文件 Test.cpp 相关联,并且只生成一次。您可以在任意数量的源文件中包含 Test.hpp,并且不会生成其他符号。

有关参考,请参阅https://en.cppreference.com/w/cpp/language/static

于 2018-09-02T09:52:50.803 回答
2

您已经声明Test::b但尚未定义它。将此行添加到您的代码中(在 Test 类之外)

int Test::b;

如果你愿意,你也可以给出一个初始值

int Test::b = 123;
于 2018-09-02T09:04:23.830 回答