头文件与类的声明
头文件的标准格式
//头文件重的防卫式声明 避免重复声明造成错误
#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);
}
- 数据一定封装在private
- 参数尽可能使用reference
- 返回值尽可能使用reference
- 构造函数使用intialization
- 应该加const 要加, 不加使用者估计会报错
- class body 外的各种定义(Definition)
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.声明周期结束就会被销毁