多态性:
多态性作用于基类和子类之间,如果基类的函数加了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”