C++(10):static、const、mutable、explicit成员

来源:互联网 发布:nginx ssl 编辑:程序博客网 时间:2024/06/05 03:05

引言


语法上说,C++可以有许多类型的成员。

1. static members
2. const members
3. mutable members
4. explicit members
5. 其他类型…
感觉用得最多的,也就是static了,const可能用一下,但究竟什么时候会写在class里面呢?
mutable类型,要让人犯晕,explicit类型,估计也就是增加程序的可读性。
成员分成员属性和成员变量,因此,4*2=8;除掉一些个别的,至少也有五六种了。
很繁琐,很复杂,很麻烦,很头晕……
因此,总结一下,方便查阅。
先摘一些资料过来。

C++ has many choices of members
– static members: members that all objects of that class share
– const members: members that require initialization and cannot be updated
– mutable members : members that need no protection from changing any time but are encapsulated in class
– explicit members: members that avoid ambiguity from calling constructor implicitly 
–and more (reference members)

static members


Class provides data encapsulation and hiding
–but results in difficulties data sharing and external visit
–can be resolved by global variables 

A better solution  static members
–is specific to one class
–has a scope shared by the objects of the same class(注意,是shared!)

比如说,银行账户是个类,每个new出来的obj,其存款利率都是一样的。
(虽然说,也完全可以不用static来写)存款利率这个变量可以写成static。

如何定义静态成员变量?
1. 静态成员变量的声明要在类内部进行。
2. 在类外面进行内存分配和初始化。
注意:not limited by the access modifier。不会因为在类内写了private,外面就不能访问。不是这样的……
class X {private://declare a static data variablestatic int count;};//initialize the static memberint X::count = 0;// 注意,这里又写了一遍int! 而且不能写static
如何访问静态成员?(这里说的是静态函数吧)
A static member can be accessed
(1) with class methods or
(2) outside class methods
一个class的类中的函数,本来就是该类所有实例共享的吧。
静态成员函数,可以在类内定义,也可以在类外定义。在类外定义的时候,前面就一定不能再写static了!
静态成员函数存在的意义在哪里?只是为了可以不new一个对象出来直接调用?还是为了达到某种全局函数的目的?
不能在static函数体内使用this指针。

const members


常量成员。e.g. 不希望被修改的数据,只读数据。

Constants almost never make sense at the object level
-- often used with static modifier  -->  这样就可以保证所有属于该类的实例共享一份这个const的成员变量。
class CScore {protected://declare a static constantstatic const int Max;};const int CScore::Max = 100; //outside class

const can used with & modifier 
-- need to be initialized in constructors
class CScore {public://declare a constant referenceconst int & sc;};
声明一个常量引用,因此在构造函数的时候,需要对这个常量引用初始化。而且,只能用参数列表进行初始化!
CScore::CScore(char *uid, char *uname,int *uscore) : sc(subj[0]) {...}

const成员数据只能由const function访问。养成好习惯。
一个成员函数,如果不会修改到数据的话,都写成const成员函数!

mutable data members


xxx,混乱……

explicit members


为了提高代码的可读性。需要显式地调用构造函数。
explicit is used to modify constructors of a class and use them explicitly.
不加explicit的构造函数
CScore::CScore(const char* cstr) {cout << cstr << endl;}
因为,java的对象必须new出来,不像C++一样,不new就在栈上,new出来的在堆上。
所以,似乎不存在这个奇异的问题。
下面一句话,其实是在构造。隐式调用构造函数。
CScore one = “Tom”; //assign or construct?
但不知道是赋值,还是构造。
加了explicit
explicit CScore::CScore(const char* cstr){ ... }
只能显式地去调用
CScore two("Jerry");

<CName> <Obj> (init_values);  --> 显式
<CName> <Obj> = (init_values);  --> 隐式


1 0