C++系列是陈旧的笔记
//eg类的成员函数和类的定义分开写
class CRectangle
{
public:
int w,h;
int area();//成员函数仅在此声明;
int perimeter();
void init(int w_,int h_);
};
//前面的CRectangle:: 代表这是一个CR类的成员函数,而非普通函数。
//那么,一定要通过对象或对象的指针或对象的引用才能调用。
int CRectangle::area(){
return w*h;
}
int CRectangle::perimeter(){
return 2*(w+h);
}
void CRectangle::init(int w_,int h_){
w=w_;
h=h_;
}
//访问范围关键字来说明类成员可被访问的范围:
private:
//私有成员,只能在成员函数内访问
public://公有成员,可以再任何地方访问
protected://保护成员
//定义一个类
class className{
private:
public:
protected://如果某个成员前面没有上述关键字,则缺省地被认为是私有成员
};
在类的成员函数内部,能够访问:
- 当前对象全部属性、函数;
- 同类其它对象的全部属性、函数
在类的成员函数以外的地方,只能访问公有成员
设置私有成员的机制,叫做“隐藏”
目的:强制对成员变量的访问一定要通过成员函数进行,那么以后成员变量的类型等属性修改后,只需要更改成员函数即可,否则,所有直接访问成员变量的语句都需要修改
- 成员函数也可以缺省和重载
- 构造函数:定义对象时必须用构造函数初始化
- 构造函数名与类名相同
析构函数
class string{
private:
char *p;
public:
string(){
p=new char[10];
}
~string();
};
string ::~string()
{
delete []p;
}
class ctext{
public:
~ctest{ cout<<"destructor called"<<endl;}
};
int main()
{
ctest array[2];
cout<<"end main"<<endl;
return 0;
}
delete 运算可以导致析构函数的调用
静态成员对象无需对象可访问
Crectangle::printtotal();//类名::成员名
CRrctangle r;r.printtotal();//对象名.成员名
CRectangle *p=&r;p->printtotal();//指针
CRectnagle & ref=r;int n=ref.ntotalnumber;//引用 引用名.成员名
Crectangle::printtotal();//类名::成员名
CRrctangle r;r.printtotal();//对象名.成员名
CRectangle *p=&r;p->printtotal();//指针
CRectnagle & ref=r;int n=ref.ntotalnumber;//引用 引用名.成员名
class complex
{
public:
double real,imag;
complex(double r=0.0,double i=0.0):real(r),imag(i){
}
complex operator-(const complex &c);
};
complex operator+(const complex &a,const complex &b)
{
return complex(a.real+b.real,a.imag+b.imag);
}//重载为普通函数,参数个数 运算符目数
complex::operator-(const complex &c)
{
return complex(real-c.real+imag-c.imag);
//重载为成员函数,参数个数为 运算符目数-1
}