《C++学习笔记》特定类型数据成员的初始化

===============================================
未完待续,转载时请表明出处:[url]http://www.cofftech.com/thread-1396-1-1.html[/url]
欢迎大家跟帖讨论哈~~~~~
===============================================

初始化列表具有多个用途:
1.主要用于向直接基类和虚基类传递参数(以后讲继承的时候我们讨论)。
2.子对象的初始化。
3.特定类型数据成员(主要是数据的引用和常量数据)的初始化。

类的特定类型数据成员包括非静态常量数据以及非静态数据(包括非静态常量数据)的引用,这些数据不能直接在构造函数中初始化。
其中非静态常量数据成员在类中以const定义,在程序运行中不准改动。例如不允许在构造函数内进行以下操作:
class X
{
int n;
const int cn;
public:
X (int j1, int j2)
{ n = j1;
// cn = j2;
// Error: Cannot modify a const object
// in function X::X(int, int)
…… }
};
同样,类中的引用也不能在构造函数中直接初始化。例如不允许以下操作:
class X
{
int n;
int& rn; // 整型引用
public:
X(int j1, int j2){… //rn = j2;…} //构造函数
// Error: Reference member ‘ rn’ is
// not initialized in function X::X(int, int)
……
};
以上数据必须使用初始化列表,见下例:
[例1]常量和引用数据成员的初始化
#include <iostream.h>
class base
{
int n;
const int cn;
public:
int& rn;
base( int j1, int j2, int& j3) : cn(j1), rn(j3)
{ // 使用初始化列表,
// here you may not use "cn = j1;" or "rn = j3;"
n = j2;
cout<<"cn is "<<cn<<endl;
cout<<"n is "<<n<<endl;
cout<<"rn is "<<rn<<endl;
}
};
void main()
{
int j = 15;
base bb(10, 20, j);
//不能使用bb(10, 20, 15),因引用rn初始化时必须使用变量j
cout<<"bb.rn is "<< bb.rn <<endl;
}
/* Results:
cn is 10
n is 20
rn is 15
bb.rn is 15(bb.rn是j的别名) */

当程序中须要定义为常量的数据成员较多时,可不必在每个数据成员前加上const关键词,只须将成员函数定义为const即可,以使程序简明。而那些可以修改的数据则可定义为mutable(mutable和const的使用更多)。见下例:
[例2]将成员函数定义为const
#include <iostream.h>
class A
{
int cons_1;
int cons_2;
mutable int noncons;
public:
A (int a, int b, int c) {
cons_1 = a;
cons_2 = b;
noncons = c;
}
void modify_show( ) const;
};
void A::modify_show ( ) const
{
int temp = 15;
cout<<cons_1<<','<<cons_2<<','<<noncons<<endl;
// cons_1 = temp;
//error C2166: l-value specifies const object
// cons_2 = temp;
//error C2166: l-value specifies const object
noncons = temp;
cout<<cons_1<<','<<cons_2<<','<<noncons<<endl;
}
void main()
{
A obj(3, 6, 9);
obj.modify_show( );
}
/* Results:
3,6,9
3,6,15 */
以上常量程序中,只准许修改mutable数据成员。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值