C++中面向对象的部分不可避免的会涉及到成员值的初始化,我们一般会采用在构造函数中给成员赋值的方式来完成初始化的工作。如下:
#includeusing namespace std; class sth { public: char* name; sth() { name = "ganlan"; } }; int main() { sth s; cout << s.name << endl; return 0; }
而其实,这种方式在执行过程中其实是有一定的损耗的,可以这样解释,第八行,在实例化的时候已经调用了默认的构造函数,所以会申请一个空间存储name,而在复写的构造函数中也需要申请一个空间存储“ganlan”,然后再赋值给name,造成空间性能的损耗。可以使用以下的案例来说明这种机制。
#includeusing namespace std; class example { public: example() { cout << "created it" << endl; } example(int x) { cout << "create it with " << x < 以上代码执行结果为:
create it create it with 1 ganlan而使用构造函数初始化列表的方法就可以避免这种情况。
#includeusing namespace std; class example { public: example() { cout << "created it" << endl; } example(int x) { cout << "create it with " << x < 注意:myExample(1) 是一种简写方式,原本需要写为myExample(example(1))
以上代码的运行结果为:
create it with 1 ganlan



