现在的位置: 首页 > 综合 > 正文

类中静态变量与const常量成员的初始化

2013年03月20日 ⁄ 综合 ⁄ 共 1071字 ⁄ 字号 评论关闭

首先看以下示例程序:

//类中,静态变量与const常量的赋值:
//static 成员在类外初始化
//const 成员(及引用成员)在类的构造函数初始化列表中初始化
//static const /const static 成员可以在类中初始化(实际上是申明)也可以不初始化,同时需要在类外定义
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class MyTestClass
{
public:
	MyTestClass() : m_ciInt(1), m_csStr("MyStr")  // const成员变量,在ctor参数列表中初始化
	{}
public:
	const int m_ciInt;
	const string m_csStr;
	static int m_siInt;
	static string m_ssStr;
	const static int m_csiInt;
	const static string m_cssStr;
};
int MyTestClass::m_siInt = 1; // static成员变量,在外部定义
string MyTestClass::m_ssStr = "MyStr"; // static成员变量,在外部定义
const int MyTestClass::m_csiInt = 1;  // const static/static const成员变量,在外部定义
const string MyTestClass::m_cssStr = "MyStr"; // const static/static const成员变量,在外部定义
class A{
	static int m;
	int n;
public:
	A(int m,int n)
	{
		this->m = m;
		this->n = n;
	}
	void print()
	{ 
		cout << m << "---" << n << endl;
	}
};
int A::m ;   //这个没有赋予初值?或者将其注销掉测试下效果
int _tmain(int argc, _TCHAR* argv[])
{
	A a1(3,4);
	A a2(5,6);
	a1.print();
	a2.print();

	return 0;
}

输出结果:

5---4

5---6

解释:

1、类中常量数据成员必须(只能)在构造函数的初始化列表中进行初始化,因为一旦进入构造函数,此常量数据成员不能再改变。注意,只能在初始化列表中进行初始化的成员还有引用成员。

2、静态变量跟构造函数没关系:构造函数是为了构造对象而定义的,而静态变量是一个类的变量,而不是不是类的对象的变量,所以自然不应该在用于构造对象的构造函数中初始化。

抱歉!评论已关闭.