好吧,我被难住了。对于静态成员变量和函数,我一直有一些困难,所以如果这个问题的答案真的很明显,我深表歉意。不过,我不知道出了什么问题。
在 WSGrid.h 中:
#include <functional>
class WSGrid
{
public:
//constructors...
static const std::function< char( void ) > _randomChar;
//private data...
};
在 WSGrid.cpp 中:
#include <random>
std::default_random_engine generator;
std::uniform_int_distribution< char > distribution;
const WSGrid::_randomChar = std::bind( distribution, generator );
在我的 main.cpp 中:
#include "WSGrid.h"
#include <iostream>
int main( int argc, char* argv[] )
{
std::cout << WSGrid::_randomChar() << std::endl;
return 0;
}
当我尝试编译 (g++ -std=c++11 -Wall -pedantic main.cpp
) 时,我得到“对 WSGrid::_randomChar 的 undefined reference ”。
所以……在我看来,我做的一切都是对的。我遵循找到的语法 here ,至少据我所知。但显然有问题。
最佳答案
您需要正确定义_randomChar
。
更新:
const WSGrid::_randomChar = std::bind( distribution, generator );
到:
const std::function<char(void)> WSGrid::_randomChar = std::bind(distribution, generator);
还需要链接WSGrid.cpp
g++ -std=c++11 -Wall -pedantic -c WSGrid.cpp -o WSGrid.o
g++ -std=c++11 -Wall -pedantic main.cpp WSGrid.o
关于C++11静态函数成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18669558/