C++面向对象开发

  • C++编程介绍
  • 头文件与类的声明
  • 构造函数
    • inline函数,如果函数在class内定义完成,则自动成为inline候选函数。        
  • /*example 1*/
    class complex
    {
    public:
        complex (double r = 0, double i = 0)
            :re(r), im(i)
        {}        /*自动inline候选*/
        complex& operator += (const complex&);
        double real() const { return re; }/*自动inline候选*/
        double imag{} const { return im; }/*自动inline候选*/
    private:
        double re, im;
        
        friend complex& __doapl(complex*, const complex&);
    };
    
    
    /*example 2*/
    inline double
    imag(const complex& x)
    {
        return x.imag();
    }
  • 构造函数可以有很多个-overloading(重载)
{
...
complex(double r = 0, double i = 0)
    :re (r), im (i)
   {}

complex() : re(0), im(0){} /*有默认参数构造函数,不能同时存在该构造函数*/

double real() const { return re; } /*?real@Complex@@QBENXZ*/
void   read(double r) { re = r; } /*?real@Complex@@QAENABN@Z*
...
}

{
    complex c1;
    complex c2();
    ...
}
  • 操作符重载
    • 操作符是如何被编译器看待的??
      {
          complex c1(2, 1);
          complex c2(5);
      
          c2 += c1; /*当编译器检测到+= 操作符的时候,会把这个操作符作用在前面的c2对象上*/
          /*
          inline complex&
          complex::operator += (this, const complex& r)
          {
              return __doapl(this, r);
          */
      }
      
      so, 如何实现操作符的重载?
      inline complex&
      __doapl(complex& ths, const complex& r)
      {
          ths->re += r.re;
          ths->im += r.im;
          return *ths;
      }
      
      /*为何返回的是complex&,而不是complex??->这样可以连续的使用操作符*/
      inline complex&
      complex::operator += (const complex& r)
      {
          return __doapl(this, r);
      }
      
      
      /*此处绝对不能用引用,因为+后的是一个临时对象,返回后就释放了,返回的引用就无效了*/
      inline complex
      operator + (const complex& x, const complex& y)
      {
          return complex(real(x) + real(y),
                          imag(x) + imag(y));
      }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值