class template 参数化类型
inline function: 函数若在 class body 内定义完成,便为 inline 函数。
access level 访问层级
参数传递:pass by value vs pass by reference(to const)
养成习惯,尽量不要 pass by value,最好所有的参数传递引用
C 中可以传递指针,四个字节
C++ 中有 reference 引用,引用在底层就相当于指针,四个字节,很快形式也很漂亮
字符只有一个字节,有时候可以考虑
传 指针 或者 引用,会修改原对象,需要考虑使用 pass by reference to const
complex& operator += (const complex&);
参数传递尽量都传引用,有时候如果考虑到小于四个字节的字符等数据,也可以传值,会更快。
return by value vs. return by reference (to const) 影响 C++ 的效率
返回值的传递尽量 by reference
complex&
double
友元 friend
在 C++ 中,被 friend 关键字修饰的函数可以自由取得 friend 的 private 成员。
相同 class 的各个 objects 互为 friends 友元
template<typename T>
class complex
{
public:
// constructor: 1. no return type; 2. same name with class name
// default arguments
// 构造函数独有一种特殊的语法,initialization list, 效率更高
complex (double r = 0, double i = 0): re(r), im(i) { }
// 这种写法不同,与上面的意思相同的,不允许这样写,会冲突,不能同时存在
// complex (): re(0), im(0) { }
// 效率低的写法,不推荐
// complex (double r = 0, double i = 0)
// { re = r;im = i; }
// 不带指针的类多半不用写析构函数!!
// 构造函数可以有很多个 - overloading 重载 ,常常发生再构造函数上。
// 相同函数名称,不同参数,不同返回类型
double real() const { return re; }
double imag() const { return im; }
int func(const complex& param)
{
// 这样直接获取 private 成员而不是通过函数是可以的,因为相同 class 的各个 objects 互为 friends 友元
return param.re + param.im;
}
private:
T re, im;
};
{
complex c1(2,1);
complex c2;
c2.func(c1);
}
设计一个 class 需要特别注意的点:
- 数据一定放在 private 中
- 参数尽可能以 reference 来传,依据实际情况决定是否添加 const
- 返回值尽可能以 reference 来传,也存在不行的情况
- 在 class body 中的这些函数,应该加 const 的就要加
- 尽量使用构造函数的特殊语法 initialization list
参数传递 或 返回值传递
什么情况下可以 pass/return by value ?什么情况下可以 pass/return by reference ?
函数具有作用域,将函数内部定义的变量以 pass by reference 形式传递返回值的时候会出现问题,因为函数执行完毕后内部的变量不存在了,reference 将会指向一个不存在的东西,这个时候就不该使用 pass by reference 的形式。
inline complex&
__doapl (complex* the, const complex& r)
{
// 第一参数将会被改动
// 第二参数不会被改动
ths->re += r.re;
ths->im += r.im;
return *ths;
}
operator overloading 操作符重载
C++ 允许操作符重载,是一个重要的语言特性。
1.成员函数
+=
二元操作符
// 这一段代码是标准库中的复数加法的实现代码!do assignment plus
inline complex&
__doapl (complex* the, const complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
inline complex&
complex::operator += (const complex& r)
{
return __doapl(this, r);
}
任何成员函数都有一个隐含的 this pointer,它指向函数的调用者。
// 这里的 this 是隐含的,编码时候不会显式的加上这个 this !
inline complex&
__doapl (this, complex* ths, const complex& r)
{
ths->re += r.re;
ths->im += r.im;
return *ths;
}
return by reference 语法分析
传递者无需知道接受者是以 reference 形式接收。
如果用 pointer 来传,传的人需要知道是一个 pointer
用 reference 来接收,速度就会快。
网友评论