第一周 C++ Boolan

一:防卫式声明

#ifndef _XXX_

#define _XXX_

#endif

 

二:头文件布局

前置声明

类声明

类定义

 

三:类声明

1.构造函数:XXX(yy r=0,yy i=0):re(r),im(i){ }

另:类型名称,避免重复多次,可以使用模板

template<typename T>      .....写在头部

{

  complex<double> c1(2.5,1.5);

  complex<int> c2(2,6);

}

 

2.构造函数被放入私有函数中,则不可以被外界调用

singleton模式中,使用此种做法

class A{

  public:

     static A& getInstance();

     setup() {}

  private:

     A();

     A(const A& rhs);

}

A& A::getInstance(){

  static A,a;

  return a;

}

 

调用方式为: A::getInstance().setup();

四:内联函数

inline,加速运行速度,是否inline则由编译器决定(由复杂程度决定)

 

五:访问级别

private:隐蔽

public:大部分函数可以使用

 

六:函数重载

重载函数,在编译器中并不重名,重新定义其名称

 

七:const

const member functions (常量成员函数)

函数中写在小括号()后->const<-大括号前{}

例如:

  class complex{

  public:

    double real() const {return re;}

    double img() const {return im;}

}

若上述const()没有写

{

  const complex c1(2,1);

  cout<<c1.real();

  cout<<c1.img();

}

其中const complex c1表示对象内容不可以更改,而调用函数时,c1.real() real可以更改对象内容而引起矛盾。

 

八:参数传递

1.若参数引用,由于传递引用。当发生改变时,传递值将发生改变。若不可改变值,则可以使用const

2.传递引用(相当于传递指针,速度更快)

 传递值时,内容过多速度慢

3.参数传递尽量传递引用

 

九:尽量返回引用

 

十:友元 friend

friend可以自由取得private成员

相同的class的各个objects互为友元

class complex{

  public:

    int func(const complex& param){

      return param.re+param.im;

  }

}

{

  complex c1(2,1);

  complex c2;

  c2.func(c1);

}

 

十:class body 外各种定义(definitions)

inline complex& _doapl(complex* ths,const complex& r){

  ths->re+=r.re;

  ths->im+=r.im;

  return *ths;

}

 

但:若声明本地变量,返回本地引用则不可取,因在函数结束时,本地变量就会销毁。所以在返回引用时考虑是否可以传递。

 

十一:运算符重载

inline complex&

_doapl(comple *ths,const complex& r){

  ths->re+=r.re;

  ths->im+=r.im;

  return *ths;

}

inline complex&

complex::operator +=(const complex& r){

  return _doapl(this,r);

}

{

  complex c1(2,1);

  complex c2(5);

  c2+=c1;

}

1.this被隐藏可以不显示表达出来

2.传递者不需要知道接受这是否以reference形式接收。

 

十二:全局函数

inline double

imag(const complex& x){

  return x.imag();

}

inline double

real(const complex& x){

  return x.real();

}

{

  complex c1(2,1);

  cout<<img(c1);

  cout<<real(c1);

}

 

十三:操作符重载

为保证客户端均可使用,可以改写成三种写法,对应三个开发函数

inline complex operator+(const complex& x,const complex){

  return complex(real(x)+real(y),imag(x)+imag(y));

}

inline complex operator+(const complex&x,double y){

  return complex(real(x)+y,imag(x));

}

inline complex operator+(double x,const complex& y){

  return complex(x+real(y),imag(y)));

}

{

  complex c1(2,1);

  complex c2;

  complex();

  complex(4,5);

}

complex()调用默认构造函数

complex(4,5);局部变量消失调用完成

 

十二:临时对象

inline complex

operator+ (const complex& x){

  return x;

}

 

转载于:https://www.cnblogs.com/memory-niu/p/8245022.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值