我创建静态数据成员的代码有什么问题?
What is wrong with my code that creates a static data member?
我只是为 static
、const
和 global
变量编写各种方案,以查看它们在哪些地方起作用,在哪些地方不起作用。
下面的代码让我感到奇怪 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
的声明也是一个定义,因为它有一个初始值设定项。只要您不获取其地址,就不需要单独的定义。
我只是为 static
、const
和 global
变量编写各种方案,以查看它们在哪些地方起作用,在哪些地方不起作用。
下面的代码让我感到奇怪 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
的声明也是一个定义,因为它有一个初始值设定项。只要您不获取其地址,就不需要单独的定义。