[C++] Class (part 2)
Members that are const or reference must be initialized. Similary, members that are of a class type that does not define a default constructor also must be initialized.
class ConstRef{
public:
ConstRef(int ii);
private:
int i;
const int ci;
int & ri;
}; ConstRef::ConstRef(int ii){
i = ii; // ok
ci = ii; // error: cannot assign to a const
ri = i; // error: ri was never initialized
}
By the time the constructor begin executing, initialization is completed. The correct way to wirtie this constructor is:
// explictly initialize reference and const members
ConstRef::ConstRef(int ii): i(ii), ci(ii), ri(i) { }
Members are initiazlied in the order in which they appear in the class definition, not the order in which they appear in the constructor initializer.
class X{
int i;
int j;
public:
// undefined: i is initialized before j
X(int val): j(val), i(j) { }
}
To avoid using members to initiazlie other members.
X(int val): j(val), i(val) { }
class Sales_data{
public:
// non-delegating constructor initialize member before corresponding argument
Sales_data(string s, unsigned cnt, double price): bookNo(s), units_sold(cnt), revenue(cnt * price) { } // remaining constructors all delegate to another constructor
Sales_data(): Sales_data('', , ) { }
Sales_data(string s): Sales_data(s, , ){ }
Sales_data(istream & is): Sales_data() { read(is, *this); }
};
Had the function bodies contain code, that code would be run before control return to the function body of the delegating constructor.
In practice, it is almost right to provide a default constructor if other constructor is defined.
class NoDefault{
public:
NoDefault( const string &);
// additional members follow, but no other constructor
}; Struct A{
NoDefault my_mem;
}; A a; // error: cannot synthesize a constructor of A Struct B{
B() { } // error: no initialization for b_member
Default b_member;
};
It is common mistake among programmers new to C++ to try to declare an object initialized with the default constructor as function
// opps! defines a function taking no parameter and returning an object of type Sales_data
Sales_data obj(); // define an object that use the default constructor
Sales_data obj;
Reference:
C++ Primer, Fifth Edition, chapter 7 Classes
最新文章
- EntityFramework 7 Migrations 迁移命令
- 【转】Tomcat中server.xml配置图
- 总结一下这几天学习django的心得
- 双向BFS
- 【HDOJ】3727 Jewel
- [XML] ResourceManager一个操作Resource的帮助类 (转载)
- Crystal Report 在 VS 2010 中的使用和发布
- 容器 What, Why, How - 每天5分钟玩转容器技术(6)
- 看我如何从一个APK到最终拿下域管理权限
- POJ 1470 Closest Common Ancestors(最近公共祖先 LCA)
- hdu1695 GCD(莫比乌斯入门题)
- calling c++ from golang with swig--windows dll (三)
- 微信域名检测的C#实现
- python的基本用法(三)字符串常用函数
- 浏览器与Tomcat交互
- HDU 2071 Max Num
- JPA+Hibernate 3.3 ——增删改查
- django 认证系统--1
- 四,ESP8266 TCP服务器(基于Lua脚本语言)
- POJ 3308 Paratroopers 最大流,乘积化和 难度:2