C plus plus day1

Header(头文件)中的防御式声明  不会有重复的include含入内容

complex.h

1 #ifndef __COMPLEX__
2 #define __COMPLEX__
3 ....
4 #endif

 构造函数名称一定要与类的名称相同

class complex
{
public:     默认实参
    complex(double r=0,double i=0)
    : re(r), im(i)   初值列 一种经典的初始化方法  和在大括号中使用 re=r; im = i; 等等价
    {} 
   double real() const {return re;} 内联函数
   下面这行 成员函数
   complex& operator += (const complex&); 返回值传递通过引用方式
private: double re,im;
   friend complex& __doap1 (complex*, const complex&) 友元 };

  inline complex&
  __doap1(complex* ths, const complex& r)
  {
  ths->re += r.re;
  ths->im += r.im;
  return *ths;

  }

 

 构造函数可以有很多同名的但接收参数的类型、个数不同 编译器会判断不同的类型来使用 重载

函数重载常常发生构造函数上

inline关键字 为了解决一些小函数大量占用内存的问题,仅是对编译器的一个建议

const表示的变量不改变数据内容

参数传递 by value and by reference   尽量不要传value 传指针  都要压倒栈中 指针只个字节 传value太大了用

返回值传递 也尽量 by reference

friend 友元   可以取得类的private成员

同一个class下的各个对象互为友元

数据一定在private里面

操作符重载 成员函数 需要使用this

                   非成员函数 不需要使用this

下面这些函数不能通过指针传递 因为他们在函数里创建的 离开这个函数就死亡了 
inline complex 比如复数的加法 对付用户的不同可能
operator + (const complex& x,const complex& y) { typename() 创建临时对象 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(1,2)临时对象

 

特殊操作符只能采用全局的写法

输出
ostream& 不能改成 void 方便使用者连续输出 operator << (ostream& os,const complex& x) { return os << '(' <<real(x)<< ',' << imag(x) << ')'; }
count << conj(1,2)<<endl;

 

posted @ 2019-03-01 20:16  碎纸屑  阅读(99)  评论(0编辑  收藏  举报