【问题标题】:What is wrong with my code that creates a static data member? [duplicate]我创建静态数据成员的代码有什么问题? [复制]
【发布时间】:2017-02-11 21:51:36
【问题描述】:

我只是在为 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

【问题讨论】:

  • Code Review 网站可能更适合这种情况。
  • 代码审查是针对工作代码的。
  • 你需要定义svec
  • Static::initVector() 也应该返回一些东西,但它没有。
  • 你应该避免使用关键字来命名你的类。看完答案我一头雾水。

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


【解决方案1】:

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

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

回答下一个问题,count 的声明也是一个定义,因为它有一个初始化器。只要不取它的地址,就不需要单独定义。

【讨论】:

  • 请注意“Static::”是类名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-29
  • 2012-07-30
  • 2013-01-23
  • 2021-08-15
  • 2011-01-18
相关资源
最近更新 更多