«

C++类的虚函数继承 && Java类的方法重写

benojan 发布于 阅读:532 编程


C++的虚函数virtual

#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
    }
}

虚函数 继承 重写