C++ 类与头文件的声明

头文件与类的声明

头文件的标准格式

//头文件重的防卫式声明 避免重复声明造成错误
#ifndef __COMPLEX__
#define __COMPLEX__

#include <cmath>


#endif

class 的声明

class Complex
{
public:
    Complex (double r =0, double i = 0)  // constructor
    : re(r), im(i)  // initialization list  
    {}  //
    // 声明且立即实现的 是内联函数 inline
    double real() const { return re;}
    double image() const { return im;}

private:
    double re, im;

    friend complex& __doapl(complex*, const complex&);

private:

};


// the instance of class
{
    Complex c1(2.5, 2.5);
    cout << c1.real() << endl;
    cout << c1.image() << endl;
}

constructor

  • constructor will be invoke when init the object
{
   Complex c1(2,1);
   Complex c2;
   Complex* p = new Complex(4,4);

}

 Complex (double r =0, double i = 0) : re(r), im(i) {} // constructor


class template

template<typename T>

class complex
{

public:

    complex (T r = 0, T i=0)
        : re(r), im(i)
    { }
    
    //
    complex& operator += (const complex&);

    T real () const { return re; }
    T imag () const { return im; }

private :
 T re, iml

 friend complex& __doapl (complex*, const complex);
    

};

{
    complex<double> c1(2.5, 2.5);

    complex<int> c2(2, 2);

}


  • class 需要注意点
  • 数据一定封装在private
  • 参数尽可能使用reference
  • 返回值尽可能使用reference
  • 构造函数使用intialization
  • 应该加const 要加, 不加使用者估计会报错
  • class body 外的各种定义(Definition)
  • do assignment plus
inline Complex&
__doaphal(Complex* ths, const complex& r)
{
    ths->re += r.re;
    ths->im += r.rm;
    return *ths;
}

inline Complex&
Complex::operator += (const Complex& r)
{
    return __doapl(this, r);
}
// 局部变量的引用不适合return.声明周期结束就会被销毁
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值