c++多态性和纯虚函数

多态性:

    多态性作用于基类和子类之间,如果基类的函数加了virtual称为虚函数,则对象调用的函数则是他自己的函数(就是子类则调用它自己的函数,不会调用基类同名的虚函数)。反之如果基类和子类之间同时存在同名函数,则调用基类函数。

#include <iostream>
using namespace std;
class animal{
	public:
		virtual void color(){
			cout << "same color !" << endl;
			}
	};

class dog : public animal{
	public:
		void color(){
			cout << "the dog color is white" << endl;
			}
};

void testContrustor(animal *animal){
	animal -> color();
	}

int main()
{
	dog dog;
	animal *animal;
	animal = &dog;
	testContrustor(animal);
    return 0;
}

结果将是: “the dog color is white”。


虚函数:

   纯虚函数是作用于基类和子类关系中,基类声明 了函数,却没有实现函数,需要在继承基类,在子类中实现该函数。声明的该函数是virtual前缀的虚函数。

// Note:Your choice is C++ IDE
#include <iostream>
using namespace std;
class animal{
	public:
		virtual void color()=0;
	};

class dog : public animal{
	public:
		void color(){
			cout << "the dog color is white" << endl;
			}
};

class cat : public animal{
	public:
		void color(){
			cout << "the dog color is black" << endl;
			}
	};

int main()
{
    dog dog;
    dog.color();
    cat cat;
    cat.color(); 
    return 0;
}
运行结果为 :“the dog color is white”和“the dog color is black”



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值