相关疑难解决方法(0)

如何在C++中初始化私有静态成员?

在C++中初始化私有静态数据成员的最佳方法是什么?我在头文件中尝试了这个,但它给了我奇怪的链接器错误:

class foo
{
    private:
        static int i;
};

int foo::i = 0;
Run Code Online (Sandbox Code Playgroud)

我猜这是因为我无法从课外初始化私人成员.那么最好的方法是什么?

c++ initialization static-members

492
推荐指数
11
解决办法
47万
查看次数

对静态类成员的未定义引用

谁能解释为什么以下代码无法编译?至少在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)

c++ g++

191
推荐指数
5
解决办法
11万
查看次数

静态变量链接错误

我在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"):'

谢谢你的帮助.

c++ xcode static-methods clang static-libraries

63
推荐指数
2
解决办法
3万
查看次数