创建静态数据成员的代码有什么问题

What is wrong with my code that creates a static data member?

本文关键字:什么 问题 代码 静态 数据成员 创建      更新时间:2023-10-16

我只是为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的声明也是一个定义,因为它有一个初始值设定项。只要你不采用它的地址,你就不需要一个单独的定义。