#include <iostream>
using namespace std;
class Father
{
public:
virtual void hello()
{
cout << "father";
}
};
class Son : public Father
{
public:
void hello()
{
cout << "son";
}
};
int main()
{
Father* f = new Son();
// 如果Father类不写virtual,则结果为father
f->hello(); // son
}
Java的类方法重写
public class Father {
public void hello() {
System.out.println("father");
}
}
public class Son {
public void hello() {
System.out.println("son");
}
}
public class Main {
public static void main(String[] args) {
Father f = new Son();
f.hello() // son
}
}