第一周(Geek Band)
2017-01-05 本文已影响0人
鬼方纾秴
C++实现数据和函数的封装

C++面向对象(ObjectOriented)



基本格式


Inline内联函数关键字
定义在class body内的function,提高处理效率。
但是是否inline由编译器决定。一般来讲,简单可以inline,复杂无法inline
如果定义在body外部的函数想要inline,函数前面加inline关键字,但是由编译器决定是否inline
Access level(访问级别)
public:外部可调用函数
private:所有数据,都应该是private,内部处理函数也是
Constructor(ctor构造函数)

Overloading(重载)
多个函数名称相同,目的相同
构造函数多发生重载
重载时编译器可以区分是哪个函数才可以重载
ctor放在private 区【singleton,单例】
不允许外界创建对象,通过类中的函数调用

常量成员函数(const)
不会改变数据,加上const 关键字,注意放置位置

参数传递(pass by value VS pass by reference [to const])

×by reference (传递引用)的速度要快过 by value(传递数值);
×指针的大小是4个字节,如果是char 只有一个字节,可以传值;
×传递引用==传递指针,这样一来可以修改数值,为了解决此问题,在引用前 加 const ;
eg: const complex&
×如果要修改值,不加const;
eg: ostream&
返回值传递(pass by value VS pass by reference [to const])
同参数传递,尽量by reference。

×传递着无需知道接收者的 接收方式(reference or value),如下图


friend(友元)

相同 class(类) 中的各个 object(对象)互为friends(友元)

不能返回reference的情况:函数内部定义的变量(本地变量)
操作符重载(operator overloading 1.成员函数;2.非成员函数)
1.成员函数
×所有的成员函数都带有隐藏的 this指针
×调用者为 this

2.非成员函数
×非成员函数操作符重载(无 this 指针),此三个函数都是全局函数。
注意返回值,均为value,因为返回的内容为临时对象(本地变量)

×typename(); 创建临时对象详解


3.全局函数定义

复习回顾:
1、数据private;
2、参数及返回值尽量 reference 传递;
3、类的body内,能加const的就加;
4、构造函数 单独:的那行注意使用

5、放在外面的函数想要内置,用 inline
6、防卫式声明


记得作业。。。