c++ - 我创建静态数据成员的代码有什么问题?

标签 c++ c++11 linker g++ ld

<分区>

我只是为 staticconstglobal 变量编写各种方案,以查看它们在哪里工作以及在哪里不工作。

下面的代码让我感到奇怪 collect2: error: ld returned 1 exit status

代码:

#include <iostream>
#include <string>
#include <vector>

using namespace std;
const static int gl = 4;
class Static{
    private:
            int nonStatic;
            const static int count = 10;
            //constexpr static string str;
            static vector<string> svec;
    public:
            static vector<string> initVector();
            void printVector();
            Static(int s=0): nonStatic(s){}
            ~Static(){}

};

vector<string> Static::initVector()
{
        for(int i=0; i<5; i++)
    {
            string str;
            cin>>str;
            svec.push_back(str);
    }
}

void Static::printVector()
{
    for(auto const i: svec)
            cout<<i;
}

int main()
{
    Static state(4);
    return 0;
}

它显示以下 ld 错误消息:

/tmp/ccsX2Fre.o: In function `Static::initVector[abi:cxx11]()':
StaticTests.cpp:(.text+0x4e): undefined reference to `Static::svec[abi:cxx11]'
/tmp/ccsX2Fre.o: In function `Static::printVector()':
StaticTests.cpp:(.text+0xc4): undefined reference to `Static::svec[abi:cxx11]'
collect2: error: ld returned 1 exit status

最佳答案

static std::vector<std::string> svec; 声明一个名为svec的静态对象类型 std::vector<std::string> .您还必须定义它。定义后Static添加定义:

std::vector<std::string> Static::svec;

为了回答下一个问题,count 的声明也是一个定义,因为它有一个初始值设定项。只要您不获取其地址,就不需要单独的定义。

关于c++ - 我创建静态数据成员的代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42181645/

相关文章:

c++ - Boost Multi-Index 中的多索引查询

c++ - Visual C++ 9.0 (2008) 静态库 + Boost 库 = 大型 .lib 文件

linker - 在调用 ELF 的默认入口点之前是否运行任何用户模式代码?

c++ - 错误LNK2019,如何解决? *更新*

C++ Makefile 头文件和 cpp

c++ - 在 C++ 源代码中使用 Unicode

c++ - 关于/kreplacements/kreplacements.h 的错误

c++ - 如何在 Windows 上部署 Qt 应用程序?

c++ - 如何有效地从给定另一个 vector 的 vector 中删除元素

C++ 线程错误 - 类参数的编译时错误