Effective C++ Item 4 确定对象被使用前已先被初始化
来源:互联网 发布:recyclerview如何优化 编辑:程序博客网 时间:2024/05/14 22:24
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
经验1:为内置对象进行手工初始化,因为C++不保证初始化它们
示例:
- int x = 0;//对int进行手工初始化
- const char *text = "A C-style string"; //对指针进行手工初始化
- double d;
- std::cin >> d;//以读取input stream的方式完成初始化
经验2:构造函数最好使用成员初值列 (member initialization list) ,而不要在构造函数本体内使用赋值操作(assignment) 。初值列列出的成员变量,其排列次序应该和它们在 class 中的声明次序相同。
示例1:用赋值操作初始化
- #include <iostream>
- using namespace std;
- class A{
- public:
- A(){cout << "default constructor" << endl;};
- A(int v):value(v){};
- A(const A &a2){cout << "copy constructor" << endl;}
- const A& operator=(const A &lhr) const{cout << "operator=" << endl; return *this;}
- private:
- int value;
- };
- class B{
- public:
- B(A a2){a = a2;}; //用赋值操作初始化
- private:
- A a;
- };
- int main(){
- A a(1);
- B b(a); //主要是通过输出看定义b变量调用的函数情况
- system("pause");
- }
输出1:
copy constructor //调用A的copy constructor为B构造函数生成参数a2
default constructor //进入B的构造函数前调用A的默认构造函数定义a
operator= //调用赋值操作符将a赋值为a2
示例2:使用成员初值列
- #include <iostream>
- using namespace std;
- class A{
- public:
- A(){cout << "default constructor" << endl;};
- A(int v):value(v){};
- A(const A &a2){cout << "copy constructor" << endl;}
- const A& operator=(const A &lhr) const{cout << "operator=" << endl; return *this;}
- private:
- int value;
- };
- class B{
- public:
- B(A a2):a(a2){};
- private:
- A a;
- };
- int main(){
- A a(1);
- B b(a);
- system("pause");
- }
输出2:
copy constructor //调用A的copy constructor为B构造函数生成参数a2
copy constructor //调用A的copy constructor将a复制为a2
0 0
- Effective C++ Item 4 确定对象被使用前已先被初始化
- Effective C++ Item 4 确定对象被使用前已先被初始化
- Effective C++(4) 确定对象被使用前已先被初始化
- Item 4:确定对象被使用前已先被初始化【effective C++读书笔记】
- Effective C++:条款04:确定对象被使用前已先被初始化
- [Effective C++]条款04 确定对象被使用前已先被初始化
- Effective C++ Item 04-确定对象被使用前以先被初始化
- Item 04:确定对象被使用前已先被初始化
- Effective C++ 04:确定对象被使用前已先被初始化
- Effective C++读书笔记---确定对象被使用前已先被初始化
- 重读经典-《Effective C++》Item4:确定对象被使用前已先被初始化
- 读书笔记《Effective C++》条款04:确定对象被使用前已先被初始化
- Effective C++——》条款4:确定对象使用前已先被初始化 .
- Item 4 :确定对象使用前已经被初始化
- Effective C++ 条款4——确定对象被使用前已先被初始化
- 《Effective C++》学习笔记条款04 确定对象被使用前被初始化
- 【Effective C++ 读书笔记】条款04:确定对象使用前已先被初始化
- effective c++ 确定对象被使用前已经被初始化
- overload与override的区别
- .Net C# Windows Service在服务器无法启动,错误 193:0xc1
- 关于Eclipse主题以及genymotion的相关设置
- BZOJ 1044 HAOI2008 木棍分割 二分答案+动态规划
- No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyIn
- Effective C++ Item 4 确定对象被使用前已先被初始化
- 关于unity的Coroutine
- 数学数分类
- freemarker中list常用处理方法
- error LNK2019: 无法解析的外部符号 __imp___CrtDbgReportW
- 百度地图 Android SDK - 标注(Marker)的基本使用
- 针对同一种类型的括号匹配问题
- 易飞9.07衍生字段删除问题
- 接口编程(webservice和post)