【20】 20_初始化列表的使用

6次阅读

共计 1682 个字符,预计需要花费 5 分钟才能阅读完成。

问题:类中是否可以定 const 成员?
小实验
下面的类定义是否合法?如果合法,ci 的值是什么,存储在哪里?
class Test
{
private:
const int ci;
public:
int getCI() { return ci};
};
编程实验:类中的 const 成员
#include <stdio.h>

class Test
{
private:
const int ci;
public:
Test()
{
ci = 10; // ERROR
}
int getCI()
{
return ci;
}
};

int main()
{
Test t;

printf(“t.ci = %d\n”, t.getCI());

return 0;
}
输出:
test.cpp:8: error: uninitialized member‘Test::ci’with‘const’type‘const int’
test.cpp:10: error: assignment of read-only data-member‘Test::ci’

类成员的初始化

C++ 中提供了初始化列表对成员变量进行初始化
语法规则

Class::ClassName() : m1(v1), m2(v1, v2), m3(v3)
{
// some other initialize operator
}
注意事项

成员的初始化顺序与成员的声明顺序相同
成员的初始化顺序与初始化列表中的位置无关
初始化列表先于构造函数的函数体执行

编程实验:初始化列表的使用
#include <stdio.h>

class Value
{
private:
int mi;
public:
Value(int i)
{
printf(“Value::Value(int i), i = %d\n”, i);
mi = i;
}
int getI()
{
return mi;
}
};

class Test
{
private:
Value m2;
Value m3;
Value m1;
public:
Test() : m1(1), m2(2), m3(3)
{
printf(“Test::Test()\n”);
}
};

int main()
{
Test t;

return 0;
}
输出:
Value::Value(int i), i = 2
Value::Value(int i), i = 3
Value::Value(int i), i = 1
Test::Test()

结论:
成员的初始化顺序与成员的声明顺序相同;
初始化列表先于构造函数的函数体执行。

发生了什么?构造函数的函数体执行前,对象已经创建完成。构造函数仅执行了对象状态的‘初始化’(实质为赋值完成,非真正意义的初始化)。初始化列表用于初始化成员,必然在类对象创建的同时进行,而非对象构造好了才进行的初始化。
类中的 const 成员

类中的 const 成员会被分配空间 (与对象分配的空间一致,堆、栈、全局数据区)
类中的 const 成员的本质是只读变量(不会进入符号表)
类中的 const 成员只能在初始化列表中指定初始值

编译器无法直接得到 const 成员的初始值,因此无法进入符号表成为真正意义上的常量。
编程实验:只读成员变量
#include <stdio.h>

class Test
{
private:
const int ci;
public:
Test() : ci(100)
{
}
int getCI()
{
return ci;
}
void setCI(int v)
{
int*p = const_cast<int*>(&ci);

*p = v;
}
};

int main()
{
Test t;

printf(“t.ci = %d\n”, t.getCI());

t.setCI(10);

printf(“t.ci = %d\n”, t.getCI());

return 0;
}
输出:
t.ci = 100
t.ci = 10

小插曲

初始化与赋值不同

初始化:对正在创建的对象(变量)进行初值设置
赋值:对已经存在的对象(变量)进行值设置

void code()
{
int i = 10; // 初始化
// …
i = 1; // 赋值
}
小结

类中可以使用初始化列表对成员进行初始化
初始化列表先于构造函数体执行
类中可以定义 const 成员变量
const 成员变量必须在初始化列表中指定初值
const 成员变量为只读变量

以上内容参考狄泰软件学院系列课程,请大家保护原创!

正文完
 0