首页 > 代码库 > 如何初始化类的static成员变量?

如何初始化类的static成员变量?

如何初始化类的static成员变量?

类的static成员变量不被某一个对象所独有,而是被所有同类型的对象所共有。

只能在头文件中声明类的static成员变量,不可在头文件中初始化,否则会造成重定义。必须在另外一个.cpp文件中进行初始化。并且,初始化的时候不可以有static修饰词。


frank@userver:~/project/test/static-test/static2_cpp$ cat static.h

#ifndef STATIC_H

#define STATIC_H


#include<iostream>

using std::cout;

using std::endl;


class TestType{

    static int m_static;

public:

    TestType(int dat = 0) {}

    void Show()const{

        cout << "this=" << this << ", ";

        cout << "m_static:(" << &m_static << ", " << m_static << ")\n";

    }

};


#endif // #ifndef STATIC_H

frank@userver:~/project/test/static-test/static2_cpp$ cat static.cpp 

#include "static.h"

int TestType::m_static = 15;

frank@userver:~/project/test/static-test/static2_cpp$ cat test.h 

#ifndef TEST_H

#define TEST_H

void test();

#endif // #ifndef TEST_H


frank@userver:~/project/test/static-test/static2_cpp$ cat test.cpp 

#include "test.h"

#include "static.h"


void test(){

    cout << __func__ << endl;

    TestType obj(5);

    obj.Show();

}

frank@userver:~/project/test/static-test/static2_cpp$ cat main.cpp 

#include "static.h"

#include "test.h"


int main(){

    cout << __func__ << endl;

    TestType obj(4);

    obj.Show();

    test();

}

frank@userver:~/project/test/static-test/static2_cpp$ g++ main.cpp test.cpp static.cpp 

frank@userver:~/project/test/static-test/static2_cpp$ ./a.out 

main

this=0x7fff309db27f, m_static:(0x602078, 15)

test

this=0x7fff309db25f, m_static:(0x602078, 15)

frank@userver:~/project/test/static-test/static2_cpp$ 


本文出自 “用C++写诗” 博客,谢绝转载!

如何初始化类的static成员变量?