一、基类和子类
基类:可以派生出其他的类,也称父类
子类:从基类派生出来的类
//Location类
class Location
{
public:
void InitL(int xx, int yy);
void Move(int xoff, int yoff);
int GetX(){return x;}
int GetY(){return y;}
private:
int x,y;
};
void Location::InitL(int xx, int yy)
{
x = xx;
y = yy;
}
void Location::Move(int xoff, int yoff)
{
x = x + xoff;
y = y + yoff;
}
//Rectangle
class Rectangle : public Location
{
public:
void InitR(int x, int y, int w, int h);
int GetH(){return h;}
int GetW(){return w;}
private:
int h,w;
};
void Rectangle::InitR(int x, int y, int w, int h)
{
InitL(x,y);
this->w = w;
this->h = h;
}
二、继承方式
首先理解三种访问级别:
- public:任何代码
- protected:类本身和子类
- private:类本身
继承方式有三种,公有继承、保护继承、私有继承
三、派生类的构造函数和析构函数
派生类对象生成时,要调用构造函数进行初始化。编译器的调用过程是先调用基类的构造函数,对派生类中的基类数据进行初始化,然后再调用派生类自己的构造函数,对派生类的数据进行初始化工作。析构函数的调用正好相反。
3.1 派生类构造函数
构造函数不可以被继承
只有当基类存在缺省参数的构造函数时候,派生类才可以省略对基类构造函数的调用
派生类构造函数的工作:
- 负责调用基类构造函数使基类的数据成员得以初始化
- 调用子对象的构造函数,对派生类中的子对象进行初始化
- 对自己的数据成员进行初始化
构造函数格式:
<派生类名>(<派生类构造函数总参数表>)
:<基类构造函数>(<参数表1>),
<子对象名>(<参数表2>)
{
<派生类中数据成员初始化>
}
若某项的参数表为空,则该项可从成员初始化列表中省略,表示使用缺省构造函数初始化该基类子对象;
#include <iostream>
class A
{
public:
A(int h,int w):he(h),we(w){}
~A()
{ cout<<he<<','<<we<<endl; }
private:
int he, we;
};
class B:public A
{
public:
B(int h,int w,int h1,int w1,int l):A(h,w),
obj1(h1,w1){len=l;}
~B(){cout<<len<<endl;}
private:
A obj1;
int len;
};
3.2 派生类析构函数
析构函数不可以被继承
析构函数的执行顺序与构造函数严格相反
#include <iostream.h>
class B
{
public:
B();
B(int i);
~B();
void Print() const;
private:
int b;
};
B::B()
{
b=0;
cout<<"B's default constructor called. "<<endl;
}
B::B(int i)
{
b=i;
cout<<"B's constructor called. "<<endl;
}
B::~B()
{
cout<<"B's destructor called. "<<endl;
}
void B::Print() const
{
cout<<b<<endl;
}
class C:public B
{
public:
C();
C(int i,int j);
~C();
void Print() const;
private:
int c;
};
C::C()
{
c=0;
cout<<"C's default constructor called. "<<endl;
}
C::C(int i,int j):B(i)
{
c=j;
cout<<"C's constructor called. "<<endl;
}
C::~C()
{
cout<<"C's destructor called. "<<endl;
}
void C::Print() const
{
B::Print();
cout<<c<<endl;
}
void main()
{
C obj(5,6);
obj.Print();
}
/************
输出:
B's constructor called.
C's constructor called.
5
6
C's destructor called.
B's destructor called.
****************/
四、多继承
4.1 多继承派生类申明形式
class A:public B2,public B1//和此顺序有关
{
public:
A(int i,int j,int k,int l);
/*** 省略 *****/
private:
int a;
B3 bb;
}
4.2 多继承构造函数格式
A::A(int i,int j,int k,int l):B1(i),B2(j),bb(k)
{
a=l;
cout<<"Constructor A. "<<endl;
}
派生构造函数存在顺序:
- 执行所有基类的构造函数,处于同一层次的各基类构造函数的执行顺序取决于定义派生类时所指定的各基类顺序
- 执行所有子对象的构造函数
- 执行派生类构造函数体