在C++中初始化私有静态数据成员的最佳方法是什么?我在头文件中尝试了这个,但它给了我奇怪的链接器错误:
class foo
{
private:
static int i;
};
int foo::i = 0;
Run Code Online (Sandbox Code Playgroud)
我猜这是因为我无法从课外初始化私人成员.那么最好的方法是什么?
谁能解释为什么以下代码无法编译?至少在g ++ 4.2.4上.
更有趣的是,为什么它会在我将MEMBER转换为int时进行编译?
#include <vector>
class Foo {
public:
static const int MEMBER = 1;
};
int main(){
vector<int> v;
v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'
v.push_back( (int) Foo::MEMBER ); // OK
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我在mac上编写C++代码.编译时为什么会出现此错误?:
体系结构i386的未定义符号:"Log :: theString",引用自:libTest.a中的Log :: method(std :: string)(Log.o)ld:未找到体系结构i386 clang的符号:错误:链接器命令失败,退出代码为1(使用-v查看调用)
不确定我的代码是否错误或者我必须向Xcode添加其他标志.我当前的XCode配置是"静态库"项目的默认配置.
我的代码:
Log.h ------------
#include <iostream>
#include <string>
using namespace std;
class Log{
public:
static void method(string arg);
private:
static string theString ;
};
Run Code Online (Sandbox Code Playgroud)
Log.cpp ----
#include "Log.h"
#include <ostream>
void Log::method(string arg){
theString = "hola";
cout << theString << endl;
}
Run Code Online (Sandbox Code Playgroud)
我用测试代码调用'方法',这样:'Log :: method("asd"):'
谢谢你的帮助.