我正在尝试在类中定义静态成员,但总是收到对静态成员的错误未定义引用。
我意识到已经有很多类似的问题。 但是在这些问题中似乎会引发错误,因为它们没有在类之外的某个地方定义静态成员。 我确信我已经定义了这些静态成员。
以下是我的代码中存在问题的部分。
在 foo.h 中,我定义了一个名为 foo 的类。
#include <random>
#include <vector>
class foo
{
public:
int random = dist(mt);
static std::random_device rd;
static std::mt19937 mt;
static std::uniform_int_distribution<int> dist;
static std::vector<int> ans(const int &);
};
在 foo.cpp 中,有静态成员的定义。
#include<random>
#include<vector>
#include "foo.h"
std::random_device foo::rd;
std::uniform_int_distribution<int> foo::dist(0, 10);
std::mt19937 foo::mt(rd());
std::vector<int> foo::ans(const int & size) {
std::vector<int> bb;
for(int i=0; i < size; ++i)
bb.push_back(dist(mt));
return bb;
}
我在另一个名为 test 的 cpp 文件中使用了该类.cpp
#include <random>
#include <vector>
#include <iostream>
#include "foo.h"
int main()
{
foo a;
std::vector<int> c=a.ans(5);
for(auto it=c.begin(); it!=c.end(); ++it)
std::cout<<*it<<"t";
std::cout<<"n";
}
有了g++ test.cpp -o a.out
,我总是收到:
/tmp/ccUPnAxJ.o: In function `main':
test.cpp:(.text+0x37): undefined reference to `foo::ans(int const&)'
/tmp/ccUPnAxJ.o: In function `foo::foo()':
test.cpp:(.text._ZN3fooC2Ev[_ZN3fooC5Ev]+0xd): undefined reference to `foo::mt'
test.cpp:(.text._ZN3fooC2Ev[_ZN3fooC5Ev]+0x12): undefined reference to `foo::dist'
collect2: error: ld returned 1 exit status'
我的 g++ 版本是:g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2,g++
是 g++ -std=c++11
的别名。
你需要:
g++ test.cpp foo.cpp -o a.out
否则,g++
怎么会知道foo.cpp
呢? 它不会根据看到#include "foo.h"
神奇地猜测.