1.1.1 ´¿Ð麯ÊýµÄÉùÃ÷ºÍ¶¨Òå
´¿Ð麯ÊýµÄÉùÃ÷¸ñʽ£º
ÔÚÀàÄÚÉùÃ÷£º
virtual º¯Êý·µ»ØÖµÀàÐͺ¯ÊýÃû(²ÎÊýÁбí)=0;
1) Ò»¸öÀàÖÐÈç¹ûÖÁÉÙÓÐÒ»¸ö´¿Ð麯Êý£¬¸Ãº¯ÊýËùÔÚµÄÀ࣬ÔòΪ³éÏóÀ࣬²»ÄÜ´´½¨³éÏóÀàµÄ¶ÔÏ󣬿ÉÒÔ´´½¨³éÏóÀàµÄÖ¸Õë
2) ³ý·ÇÔÚÅÉÉúÀàÖн«»ùÀàµÄËùÓеĴ¿Ð麯ÊýÈ«²¿¶¼ÊµÏÖ£¬¸ÃÀ಻ÔÚÊdzéÏóÀ࣬»ùÀàµÄÅÉÉúÀàÒ²ÓпÉÄÜÊdzéÏóÀàÐÍ
3) ÅÉÉúÀàÈç¹ûÒÀÈ»ÎÞ·¨ÊµÏÖ´¿Ð麯Êý£¬ÔòÐèÒª½«ÆäÔÙ´ÎÉùÃ÷Ϊ´¿Ð麯Êý
1.1.2 ³éÏóÀà
Ò»¸öÀà¿ÉÒÔ°üº¬¶à¸ö´¿Ð麯Êý¡£Ö»ÒªÀàÖк¬ÓÐÒ»¸ö´¿Ð麯Êý£¬¸ÃÀà±ãΪ³éÏóÀà¡£Ò»¸ö³éÏóÀàÖ»ÄÜ×÷Ϊ»ùÀàÀ´ÅÉÉúÐÂÀ࣬²»ÄÜ´´½¨³éÏóÀàµÄ¶ÔÏó£¬ÈçÀýÖеÄAÀà±ãÊdzéÏóÀ࣬´´½¨AÀàµÄ¶ÔÏóÊÇ·Ç·¨µÄ£¬È磺
A a; //´íÎó£ºAΪ³éÏóÀà
µ«¿ÉÉùÃ÷Ò»¸öÖ¸Ïò³éÏóÀàµÄÖ¸Õ룬È磺
A* a=NULL;
A* a=new B; //ÕýÈ·£¬´´½¨BµÄ¶ÔÏó
ӦעÒ⣺¡°A* a=new A;¡±·Ç·¨£¬ÒòΪ¸ÃÓï¾äÊÔͼ´´½¨AµÄ¶ÔÏó¡£
ºÍÆÕͨµÄÐ麯Êý²»Í¬£¬´¿Ð麯Êý²»Äܱ»×Ô¶¯¼Ì³Ð£¬ÔÚÅÉÉúÀàÖбØÐë¶Ô»ùÀàÖÐÐ麯Êý½øÐÐÖض¨Ò壬»òÕßÔÚÅÉÉúÀàÖÐÔٴν«¸ÃÐ麯ÊýÉùÃ÷Ϊ´¿Ð麯Êý£¬·ñÔò±àÒëÆ÷½«Ìáʾ´íÎóÐÅÏ¢¡£Õâ˵Ã÷£¬³éÏóÀàµÄÅÉÉúÀàÒ²¿ÉÒÔÊdzéÏóÀֻ࣬ÓÐÔÚÅÉÉúÀàÖиø³öÁË»ùÀàÖÐËùÓд¿Ð麯ÊýµÄʵÏÖʱ£¬¸ÃÅÉÉúÀà±ã²»ÔÙÊdzéÏóÀà¡£ºÍ´¿Ð麯ÊýÒ»Ñù£¬³éÏóÀàÖ»Æðµ½Ìṩͳһ½Ó¿ÚµÄ×÷Óá£
#include <iostream>
using namespace std;
class Base //³éÏóÀà { public: virtual void show() = 0; virtual void fun() = 0; //ÉùÃ÷Ϊ´¿Ð麯Êý };
class Child2 :public Base { public: virtual void show() = 0; //ÎÞ·¨ÔÚÅÉÉúÀàÖÐʵÏÖ¶¨Ò壬ÔòÐèÒª½«Æä¼ÌÐøÉùÃ÷Ϊ´¿Ð麯Êý void fun(){ cout << "ChildÀàµÄfunº¯Êý" << endl; } //Ð麯Êý
};
class Child :public Base { public: void show(){ cout << "ChildÀàµÄshowº¯Êý" << endl; } void fun(){ cout << "ChildÀàµÄfunº¯Êý" << endl; } //Ð麯Êý
};
int main() { Base *pa; Child2 *pchild2; Child child;
pa = &child; pa->fun(); pa->show();
} |