Static data members of the class (C++)

  • Static const members can use in-place initialization
class A{
    
    
	static const int static_const_member = 4;	// 正确
	static int static_member = 3;				// 出现错误:error: ISO C++ forbids in-class initialization of non-const static member 'A::static_member' static int static_member = 3;
};
  • Static non-const members can only be initialized outside the class
class A{
    
    
	static const int static_const_member = 4;
	static int static_member;	// 类内声明
};
int A::static_member = 3;		// 类外定义并初始化
  • Note on the declaration and definition of static members:
  1. For static non-const members must be defined outside the class, inside the class is only declarative
  2. For a static const member, you can only declare it in the class without defining it, but at this time the member must be an integer type (char, bool, short), and the member cannot be addressed, otherwise the compiler will report an error because the member has not been definition.
  3. For static const members, if there is no initial value assigned in the class, you must define and assign the initial value outside the class; if you assign the initial value in the class, you can no longer assign it when you need to define it outside the class.
#include <iostream>

#define INT 1
using namespace std;

class A{
    
    
public:
	static int a;					// 声明式,必须在类外定义

	// error: 'constexpr' needed for in-class initialization of static data member 'const double A::b' of non-integral type [-fpermissive]
	// static const double b = 20.0;	// 声明式,编译器报错,必须是整数类型,例如,int、 bool、 char
	
	static const int c = 20.0;		// 声明式,如果不在类外提供定义,则不能对它进行取地址运算。否则编译器报错

	static const int d = 20.0;		// 声明式,在类外提供定义

	static const int e;				// 声明式,在类外定义
};

int A::a = 9;	// 类的静态非const成员必须在类外定义

const int A::d;	// 类的静态const成员可以选择性地提供定义,非必须。如果不提供定义就不应该对它进行取地址运算。

// 下面对d的定义出错,因为已经在声明处赋予了初始值。
// error: duplicate initialization of 'A::d'
// const int A::d = 5;

const int A::e = 4;

// 下面对e的定义出错,因为e是const成员,而且在类中声明时并没有给定初值。
// error: uninitialized const 'A::e' [-fpermissive]
// const int A::e;


int main() {
    
    
	int *pa = &A::a;
	cout << "A::a = " << *pa << endl;

	// 下面语句将报错“(.text+0x58): undefined reference to `A::c'”
	// const int *pc = &A::c;

	const int *pd = &A::d;
	cout << "A::d = " << *pd << endl;

	const int *pe = &A::e;
	cout << "A::e = " << *pe << endl;

}

Guess you like

Origin blog.csdn.net/weixin_40315481/article/details/107905386