C缺点:各个函数都可以去处理数据,数据与函数是分开的,相当于数据是全局的,用到的时候函数拿过来用。
但是C++:将数据与函数包在一起。
头文件的写法:
complex.h
#ifndef _COMPLEX_ #防卫式声明
#define _COMPLEX_
……
#endif
头文件的布局
- 前置声明:
如: #include
class complex; - 类声明 class complex{……};
- 类定义 complex ::function……
按照此布局写一个复数
class complex;
{
public:
complex(double r=0,double i=0)
:re(r),im(i)
{}
complex &operate+=(const complex &); #声明
double real() const {return re;}
double real() const {return im;}
private:
double re ,im;
friend complex& _doapl(complex*,const complex&);
}; #一个body 结束
导入一个模板,目的是为了不把数据类型写死。
template<typename T>
class complex;
{
public:
complex(double r=0,double i=0)
:re(r),im(i)
{} #构造函数特有的方法 将r设给re;也就是我们常看到的初始
complex &operate+=(const complex &); #声明
double real() const {return re;}
double real() const {return im;}
private:
T re ,im;
friend complex& _doapl(complex*,const complex&);
}; #一个body 结束
{
complex<double> c1(2.5,1.5); #T替换掉
complex<int>c2(2,6);
}
重载函数
- 同名的函数可同时存在,实则编译器其实识别是不同的
- 重载常发生在构造函数身上
- 写构造函数会友冲突的
一,inline函数:
为了解决一些频繁调用的小函数大量消耗栈空间(栈内存)的问题,特别的引入了inline修饰符,表示为内联函数。
如果函数太复杂,编译器是没有能力inline。最后是由编译器决定的。
二,访问级别:
也就是public 和 private
也就是数据的部分可以是private ,因为数据是封装的。而函数部分可以是public 的,因为函数是公用的。
三,构造函数:
注意:
5. 与类一致
6. 无返回类型
构造函数就是用来创建对象。对象是什么,即例子中的complex。所以不必写,也没有返回类型。
四,常量成员函数
形式:double real () const {return re;}
五,参数传递:
class complex
{
public :
complex(double r=0, double i=0)
: re (r) ,im(i)
{}
complex& operate +=(const complex&);
double real () const {return re};
double imag () const {return im};
private:
double re,iml
friend complex& _dopal (complex* , const complex&);
}
ostream&
operator << (ostream& os,const complex& x)
{
return os << '(' << real (x) ','
<< imag (x) << ')';
}
这里是传引用,类比C语言中的存指针。
引用
int& r = i;
double& s = d;
读作:r 是一个初始化为 i 的整型引用
例程:
#include <iostream>
using namespace std;
int main ()
{
// 声明简单的变量
int i;
double d;
// 声明引用变量
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
const complex& : 传递一个数给你,但是速度很快。并不希望你更改。
同理,返回值也尽量by reference
六,友元 friend:
朋友可以过来拿你的数据。
朋友就打破了封装。
或者换一方方法,不通过friend 获取,而是通过函数来拿
即:
private:
double re,im;
friend complex __dopal (complex*,comst complex&);
complax 的函数:
inline complex&
__dopal (complex* ths ,const complex& r )
{
ths ->re +=r.re;
ths->im+=r.im; #直接去那内部的数据,并没有通过哪个函数
return *ths;
}
七,相同的class的各个objects互为friend(友元)
class complex
{
public:
complex(double r=0,double i=0)
:re (r),im (i)
{}
int func(const complex& param)
{
return param.re + param.im;
}# 设计了一函数func,但是没有用函数来取实部虚部,难道没有破环封装性吗?
private :
double re ,im;
};
{
complex c1(2,1);
complex c2;
c2.func(c1);
}
八,class body 外的各种定义
inline complex&
__dopal(complex* ths , const complex& r) #参数1本身就存在
{
ths ->re+=r.re;
ths-> im+=r.im;
return *ths;
}
inline complex&
complex::operator +=(const complex& r)
{
return __dopal (this,r);
}
总结:
怎么写类?
- 数据一定放在private里
- 参数,返回值都尽可能的用引用来传
- 要不要加const,看具体的情况
- 构造函数的用法学会用