c++ 类内static成员初始化

时间:2021-07-18 06:01:16

类内部的static成员,除了为const static 且为整数类型(int char bool)可在类内部初始化。

其他的都建议在对应的cpp文件中进行初始化。

test.h

#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED

class B {
public:
    B();
    B(int a);
    void print () const;
};

class A {
public:
    const static B a;
    const static int x = 100;
};

#endif // TEST_H_INCLUDED

 

test.cpp

#include <iostream>
#include "test.h"

B::B() {
    std::cout << "B construct" << std::endl;
}

B::B(int x) {
    std::cout << "B construct x" << std::endl;
}

void B::print() const {
    std::cout << "B print" << std::endl;
}

const B A::a(1);