1.防卫式声明
complex.h
#ifndef __COMPLEX__
#define __COMPLEX__
...
#endif
作用:在其他cpp文件中,include"complex.h"不重复含入,含入一次即可。
2.h文件中写复数加减法
complex.h
#ifndef __COMPLEX__
#define __COMPLEX__
class complex
{
public: //需要被外界使用的函数放到public里
...
private: //数据的部分放到private
double re,im;
...
protected: //保护的
};
{
complex c1(2,1);
complex c2;
}
...
#endif
ps:不能取private中的数据。只能取pubilc中的函数。
3.构造函数
ps:红色部分是构造函数,要与类名一致,不需要有返回值。作用是创建对象,做初始化等。
4.构造函数的重载
可以重名,但是参数不同。
5.定义函数时加const
3.模版
考虑上面的代码,如果有的需求是double re,im,有得是int re,im,或者其他类型。这时候如果每个类型都重新定义一个类就太重复了。引入类的概念。
complex.h
#ifndef __COMPLEX__
#define __COMPLEX__
template<typename T>
class complex
{
public:
...
private:
T re,im;
...
};
{
complex<double> c1(2.5,1.5);
complex<int> c2(2,6);
}
...
#endif