面向对象开发
课程代码实例
class complex
{
public:
complex(double r = 0, double i = 0)
: re(r), im(i)
{}
complex& operator += (const complex&)
double real () const { return re; }
double imag () const { return im; }
private:
double re, im;
friend complex& __doapl (complex* , const complex&);
}
头文件与类声明
- 类声明中的防卫式声明
#ifndef __COMPLEX__
#define __COMPLEX__
code Part
#endif
- 头文件布局
- 前置声明
- 类声明
- 类定义
PS: 模版在使用时,可通过此方式来标识typename的类型complex()
构造函数
// initialization list
// 构造函数的特有手段
complex(double r = 0, double i = 0)
: re(r), im(i)
{}
// 效果同
complex(double r = 0, double i = 0){
re = r;
im = i;
}
- 差异分析,一个变量赋值分为了两个过程
- 1、初始化 2、赋值
- 方式1效率更高,在初始化的阶段就可完成赋值操作
// 函数重载冲突
complex(double r = 0, double i = 0)
: re(r), im(i)
{}
complex() : re(0), im(0) { }
// 当发生次初始化时,会出现问题
// 编译器无法选择
complex data();
// 默认为inline函数
double real () { return re; }
double imag () { return im; }
// 可在外部声明
inline double
complex::real(){
return re;
}
- inline函数仅可用于简单函数
- inline有着高效的特点
- inline仅向编译器提供建议,具体是否以inline方式运行由编译器决定
// const 用于指示当前函数不可修改其成员
double real () const { return re; }
double imag () const { return im; }
// 此外
complex object;
object.real(); // 正确
const complex object2;
object2.real();
/*
若无const,则编译器声明该对象为常量对象
函数声明该对象变量可修改,产生冲突
编译器故会报错
*/
参数传递与返回值
singleton 模式
// 构造函数在此案例中位于private区
class A{
public::
static &A getInsttance();
setup() {...}
private:
A();
A(const A& rhs);
...
}
A& A::getInstance(){
static A a;
return a;
}
passByvalue Or passByreference
complex& operator += (const complex&)
- 问题的考量其实在于性能上的最优解
- 采用refer进行传参时,消耗内存始终为4B
- 故当我们的参数为char等类型时,传val是一个更为高效的用法
- 当参数为自定结构体或者对象时,传refer无疑是个更为高效的用法
- 至于当我们当心passByrefer这种方式会造成相关变量修改时,我们通过const限定即可
returnByvalue Or returnByreference
complex& operator += (const complex&)
- 问题的考量则一般在于是否需要新的内存
int sum = a + b
执行此操作时,我们选择refer显然会造成返回值得丢失int sum += a
执行此操作时,一般同样以开销为由建议选择refer
friend
friend complex& __doapl (complex* , const complex&);
- 友元:自由取得friend的private成员
// 传输者无需在意是否以refer接收
inline complex&
complex::__dopal(complex* ths, const complex& r){
ths->re += r.re;
ths->im += r.im;
return *ths;
}
// 另一种实现方法
// 原理:相同class的各个objects互为友元
int func(const complex& param){
return param.re + param.im;
}
- 考虑准则
-
构造函数尽量采用初始化的方式为变量赋值
-
数据成员在private中、
-
参数尽量以refer形式传递(const视情况添加)
-
返回值尽量以refer形式传递
-
classBody中的函数尽量添加const声明
-
操作符重载与临时对象
// 连串使用时,return不可以是val
inline complex&
complex::operator += (const complex &r){
return ___doapl(this, r);
}
- 你可能会好奇此处的this,这是类中函数所特有的隐藏参数
临时对象
complex()
生命周期仅有一行
<<运算符重载
ostream&
operator << (ostream& os, const complex& x)
return os << '(' << real(x) << ',' << imag(x) << ')';
// 此处将返回值类型改为void,会造成的问题
// 不支持如下语句
cout << c1 << conj(c1);