类和类的关系
1、组合关系 has_a a part of 一部分(链表结点是链表的一部分)
2、继承关系 is_a(公有继承) a kind of 一种(学生是人的一部分)
3、代理关系 has_a(私有继承) 限制底层的接口,对外提供新的特性(如:容器适配器的实现,写了个栈,里边有个vector)
同名函数的关系
1、重载(overload)
同作用域 同名 参数列表不同
2、隐藏(overhide)有函数存在但是看不见
作用域不同,在继承关系中 隐藏了基类中所有的同名函数
3、覆盖(override) 替换了、函数不存在
#include<iostream>
using namespace std;
class Base
{
public:
Base(int a = 0) :ma(a)
{
cout << "Base::Base()" << endl;
}
void show()//1
{
cout << "Base::show()" << endl;
cout << ma << endl;
}
void show(int rhs)//2
{
cout << "Base::show(int)" << endl;
int sum = ma + rhs;
cout << sum << endl;
}
protected:
int ma;
};
class Derive:public Base
{
public:
Derive(int b) :mb(b), Base(b)
//因为基类中没有默认构造函数,只有加参数的构造函数,
//所以在此参数列表中要加Base(b)来指明基类的构造方式
{
cout << "Derive::Derive()" << endl;
}
void show()//3
{
cout << "Derive::show()" << endl;
cout << mb << endl;
}
private:
int mb;
};
int main()
{
Derive derive(10);
derive.show();
//derive.show(10);//err 子类隐藏了父类中的1、2,在此只能看到子类中的3
//要是想调用2,需要加作用域,如下:
derive.Base::show(10);
}
派生类的构造和析构顺序:(先构造的后析构)
扫描二维码关注公众号,回复:
5009096 查看本文章
构造:先基类后派生类
析构:先派生类后基类
基类和派生类的互相指向
#include<iostream>
using namespace std;
class Base
{
public:
Base(int a = 0) :ma(a)
{
cout << "Base::Base()" << endl;
}
void show()//1
{
cout << "Base::show()" << endl;
cout << ma << endl;
}
void show(int rhs)//2
{
cout << "Base::show(int)" << endl;
int sum = ma + rhs;
cout << sum << endl;
}
protected:
int ma;
};
class Derive:public Base
{
public:
Derive(int b) :mb(b), Base(b)
//因为基类中没有默认构造函数,所以在此参数列表中要加Base(b)来指明基类的构造方式
{
cout << "Derive::Derive()" << endl;
}
void show()//3
{
cout << "Derive::show()" << endl;
cout << mb << endl;
}
private:
int mb;
};
//int main()
//{
// Derive derive(10);
// derive.show();
// //derive.show(10);//err 子类隐藏了父类中的1、2,在此只能看到子类中的3
// //要是想调用2,需要加作用域,如下:
// derive.Base::show(10);
//}
int main()
{
//基类指针指向派生类对象
Base* pb = new Derive(10);//ok
//派生类(学生)指针不允许指向基类(人)对象
//Derive* pd = new Base(10);//err
}