Type compatible with the principle of encounter function overrides

1, object-oriented new demands

The compiler approach is not what we expected

         The actual type of the object is determined to rewrite the function calls

         If the parent class is a pointer to the parent class object defined in the parent class is called

         If the parent class is a pointer to the subclass object subclass override function defined it is called

This new demand is polymorphic


#include<iostream>
using namespace std;


class Parent
{
public:
	Parent (int a)
	{
		this->a = a;
		cout<<"a: "<<a<<endl;
	}
	virtual void print()//在父类同名函数写了virtual关键字后子类可写可不写
	{
		cout<<"Parent 打印a: "<<a<<endl;
	}
protected:
private:
	int a;
};


class child:public Parent
{
public:
	child (int b):Parent(10)
	{
		this->b = b;
		cout<<"b: "<<b<<endl;
	}
	void print()
	{
		cout<<"Child 打印b: "<<b<<endl;
	}
protected:
private:
	int b;
};

void howToPrint(Parent *base)
{
	base->print();
}

void howToPrint2(Parent &base)
{
	base.print();
}



int main()
{
	Parent *base = NULL;
	Parent p1(20);
	child c1(30);

	base = &p1;
	base->print();//执行父类的大隐函数

	base = &c1;
	base->print();//执行谁的函数?----面向对象新需求
	
	{
		Parent &base2 = p1;
		base2.print();
	
		Parent &base3 = c1;//base3是c1的别名
		base3.print();
	}

	//函数调用
	howToPrint(&p1);
	howToPrint(&c1);

	howToPrint2(p1);
	howToPrint2(c1);
	

	system("pause");
	return 0;
}




Published 33 original articles · won praise 2 · Views 8516

Guess you like

Origin blog.csdn.net/QQ960054653/article/details/60962050