608a.cpp

来自「C++实训教程」· C++ 代码 · 共 47 行

CPP
47
字号
//608a.CPP demo polimorphism and virtual function
#include <iostream.h>
#include <cstring.h>
class Person
{
protected:
	string name;
public:
	Person(){name="";}
	Person(string n){name=n;}
	void PutName(string s) { name=s; }
	virtual   void ShowInfo(void)   { cout <<"Name is " <<name<<endl; }
};

class Address:public Person
{
	string addr;
public:
	Address():Person(){addr="";}
	Address(string aa,string nn):Person(nn){addr=aa;}
	void PutAddress(string a)	{ addr=a; }
	void ShowInfo(void)
   {	cout <<"Name is " <<name << "  Addr. is "<<addr << endl;	}
};
main(void)
{
	Person *prtP, objP("PeiPei");
	Address objA("New Zeland","Black");
	prtP=&objP;		// address of base
	prtP->ShowInfo( );

	prtP=&objA; // Access class Address via base pointer.
	prtP->ShowInfo( );

	return 0;
}
/*
Name is PeiPei
Name is Black  Addr. is New Zeland

*/
/* if without virtual:
Name is PeiPei
Name is Black

*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?