派生对象和基类对象指针的使用(类型兼容性规则)

【问题描述】声明-个基类BaseClass,从它派生出类DerivedClass,BaseClass有成员2数fnl()、fn2(),DerivedClass也有成员函数fnl()、fn2(),在主函数中声明向DerivedClass的对象,分别用DerivedClass的对象以及BaseClass和DerivedClass的指针来调用fnl()、fn2(),观察运行结果。

【输入形式】无输入。

【输出形式】分别输出调用指定函数之后的指定信息。

【样例输入】无输入

【样例输出】

the fn1 founction of the DerivedClass

the fn2 founction of the DerivedClass

the fn1 founction of the baseclass

the fn2 founction of the baseclass

the fn1 founction of the DerivedClass

the fn2 founction of the DerivedClass

【程序说明】各个函数的实现中,只需要有相应的函数调用输出信息就可以了。

主函数中函数调用的依次为:DerivedClass对象调用函数fnl()、fn2();BaseClass类型指针指向DerivedClass对象调用函数fnl()、fn2();DerivedClass类型指针指向DerivedClass对象调用fnl()、fn2();

需要仔细观察调用的输出信息,理解类型兼容性原则和指向对象的指针。

#include<iostream>
using namespace std;
//基类
class BaseClass
{
public:
	void fn1()
	{
		cout << "the fn1 founction of the baseclass\n";
	}
	void fn2()
	{
		cout << "the fn2 founction of the baseclass\n";
	}
};
//派生类
class DerivedClass : public BaseClass
{
public :
	void fn1()
	{
		cout << "the fn1 founction of the DerivedClass\n";
	}
	void fn2()
	{
		cout << "the fn2 founction of the DerivedClass\n";
	}
};
int main() {
	//派生类对象
	DerivedClass example;
	//基类指针
	BaseClass* p;
	//派生类指针
	DerivedClass* p2;
	//DerivedClass对象调用
	example.fn1();
	example.fn2();
	//基类指针指向派生类对象
	p = &example;
	//基类指针调用
	p->fn1();
	p->fn2();
	//派生类指针指向派生类对象
	p2 = &example;
	//调用
	p2->fn1();
	p2->fn2();

}