Object and Class
1. Type
指定一个基本类型:
- 需要多少内存进行存储
- 如何解释(转换)内存中的位
- 决定可执行的操作符运算或是函数
2. Class
- class declaration: 成员变量、函数的声明
- class method definitions: 具体函数的定义(实现)
2.1 Access Control
默认,类成员为私有
- Abstraction component: 公有接口
- Encapsulation component
2.2 Inline function
- 在声明类时所定义的方法为inline函数: 此处的
set_tot
为inline function
Class Stock
{
private:
...
void set_tot() { total_val = shares * share_val; }
}
- 通过添加关键字
inline
可使得定义在声明以外的函数也获得inline特性
Class Stock
{
private:
...
void set_tot();
}
inline void Stock::set_tot()
{
total_val = shares * share_val;
}
inline function 可视为class中的宏函数定义,可以增加运行效率,减少内存开销,但与宏函数不同,其不仅仅是简单的替换,编译器会对inline函数做一定的检查,区别如下:
// 宏函数
#define macro_test(b,c) (b*c)
// 内联函数
inline int inline_test(int b,int c)
{
return b*c;
}
// macro_test(5-2,3): -1 (5-2*3)
// inline_test(5-2,3): 9 ((5-2)*3)
因此,inline function适用于较为短小的函数,且inline关键字只用作建议编译器将函数视为inline,实际运行中,编译器可能忽略此意见。
2.3 Constructor and Destructors
2.3.1 Constructor
- 显式调用
Stock food = Stock("a",1,2);
- 隐式调用
Stock food("a",1,2);
- 默认构造函数
- 当没有任何构造函数时,编译器自动提供默认函数
- 一旦有任何构造函数存在时,必须自定义一个默认函数,否则会报错
class Stock{
public:
Stock(int a);
}
Stock stock1;// 报错
- 构造函数用于赋值
Stock stock1 = Stock("a");
stock1 = Stock("b"); // 创建临时变量stock1
- 定义默认构造函数
- 重载默认构造函数
Stock()
- 为构造函数提供默认值
Stock(int a=0)
- 一个类只能拥有一个默认构造函数
- 隐式地调用默认构造函数不要使用括号
Stock stock;
- 重载默认构造函数
2.3.2 Destructors
当函数过期时,调用解构函数,解构函数细节如下:
- 函数名:
~Stock()
- 无返回值,无返回类型定义(这点同构造函数)
- 不能拥有参数!
编译器决定何时调用解构函数,一般不显式调用解构函数。
2.4 成员名与参数名
成员名与参数名不能相同,可以给成员名加上_m
前缀或是_
后缀以示区别。
2.5 C++11 list initialization
Stock s1 = {"a"};
Stock s2{"b"};
Stock s3{};
2.6 constant member function
函数show()
并不改变类变量,使用show() const
声明。
2.7 this porinter
this
用来指明当前变量的指针。
2.8 An Array of Objects
初始化对象数组的方案是,首先使用默认构造函数创建数组元素,然后花括号中的构造函数将创建临时对象,然后将临时对象的内容复制到相应的元素中。因此,要创建类对象数组,则这个类必须有默认构造函数。
2.9 Class Scope
在创建类的实例前,没有地方用于存放变量,因此如下的定义在类中是不可行的:
class Bakery{
private:
const int Months = 12; // 出错
}
- 使用枚举类型: 不创建类数据或成员,只创建符号常量
Month
,编译器将Month
简单替换为12
class Bakery{
private:
enum {Month=12};
}
- 使用
static
关键词: 创建静态变量
class Bakery{
private:
static const int Month = 12;
}
作用域中的枚举
- 当声明如下枚举类型时,会出错
enum egg {small,big};
enum t_shirt {small,big};
- 所以可以添加
class/struct
作用域以示区分
enum class egg {small,big};
enum struct t_shirt {small,big};
egg choice = egg::small;
t_shirt c = t_shirt::small;