C++静态方法调用静态变量报错:undefined reference to 'namespace::class::field'

来源:互联网 发布:绘制示意图软件 编辑:程序博客网 时间:2024/05/17 04:28

        作为一个之前一直习惯写java的coder来说,开始写C++时候会有各种不习惯的问题,本来感觉是个显而易见的东西,编译却发现会报错,今天就说一下在C++类里一个静态方法调用静态变量时出现的错误,开始写的代码如下:

功能很简单,有个静态的test方法,两个静态变量,希望在test里进行调用

头文件:test.h,

 namespace test{
class Test{ 
public:
    static void test();
    static int testInt;  
    static const char * testCode;
};

 }

cpp文件:test.cpp

namespace test{
class Test{
 void Test::test(){

testInt=10;

testCode="test";

}

 }

恩,完成,感觉这应该没啥问题,但是编译会报错:undefined reference to 'test::Test::testInt'....字面意思是没定义,有点摸不着头脑,这怎么可能有问题呢,后来google了一番才发现,这种情况需要在cpp文件里,对变量进行显示的初始化才可以,注意是在cpp文件里,对test.cpp文件进行如下修改:

namespace test{

int Test::testInt=0;

const char* Test:: testcode="test";

class Test{
 void Test::test(){

testInt=10;

}

 }

这样之后就可以顺利运行了。



0 0
原创粉丝点击