在C++里的多态性是通过基类里声明的虚函数,当子类重新实现父类里的虚函数时,通过基类指针变量指向派生类对象就可以调用到派生类最新实现的函数功能.
class Animal {
public:
virtual void eat() {
// virtual只要在基类的函数里声明一次就可以了,所有的派生类都会有这个虚函数
cout << "animal eats" << endl;
}
};
class Dog : public Animal {
public:
void eat() {
cout << "dog eats" << endl;
}
};
class MadDog : public Dog {
public:
void eat() {
cout << "maddog eats" << endl;
}
};
int main(void)
{
Animal *a = new MadDog; //基类指针变量指向派生类对象
a->eat(); //MadDog的eat()函数就会得到调用
return 0;
}
在c++里需要用关键字”virtual”声明函数才会具体虚函数的功能。
在java里无需声明所有的函数就已经具本虚函数的功能了.
class Animal {
public void eat() {
System.out.println("animal eats");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("dog eats");
}
}
class MadDog extends Dog {
public void eat() {
System.out.println("maddog eats");
}
}
public class Hello {
public static void main(String[] args) {
Animal a = new MadDog(); //基类指针变量指向派生类对象
a.eat(); //调用MadDog的eat()函数
}
}
本文通过C++和Java两种语言的示例代码详细解释了多态性的概念及其实现方式。C++中使用virtual关键字声明虚函数来实现多态,而Java则默认所有方法均可被覆盖。
3334

被折叠的 条评论
为什么被折叠?



