对于基类中的虚函数,在派生类中写一个同名但函数前面不同的函数,导致的是覆盖而不是重写,通过基类指针(引用)无法正确地调用派生类函数(多态)。

    1. #include <iostream>
    2. #include <cstring>
    3. #include <vector>
    4. #include <new>
    5. using namespace std;
    6. class Base {
    7. public:
    8. virtual void Fun() const {
    9. cout << "Base Fun" << endl;
    10. }
    11. };
    12. class Derive
    13. : public Base {
    14. public:
    15. virtual void Fun() { // 这里没加const
    16. // 此时在这个函数后面加上override会报错
    17. // 所以在重写函数时加上override可以在编译期发现问题
    18. cout << "Derived Fun" << endl;
    19. };
    20. };
    21. int main() {
    22. Base b;
    23. Derive d;
    24. b.Fun();
    25. d.Fun();
    26. const Base *pb1 = &b;
    27. const Base *pd1 = &d;
    28. pb1->Fun();
    29. pd1->Fun();
    30. // const Base *pb2 = &b;
    31. // const Derive *pd2 = &d;
    32. // pb2->Fun();
    33. // pd2->Fun(); // 编译错误
    34. return 0;
    35. }

    image.png
    必须要函数签名一样才是重写,才能正确地多态调用。

    1. #include <iostream>
    2. #include <cstring>
    3. #include <vector>
    4. #include <new>
    5. using namespace std;
    6. class Base {
    7. public:
    8. virtual void Fun() const {
    9. cout << "Base Fun" << endl;
    10. }
    11. };
    12. class Derive
    13. : public Base {
    14. public:
    15. virtual void Fun() const override { // 加上了const
    16. cout << "Derived Fun" << endl;
    17. };
    18. };
    19. int main() {
    20. Base b;
    21. Derive d;
    22. b.Fun();
    23. d.Fun();
    24. const Base *pb1 = &b;
    25. const Base *pd1 = &d;
    26. pb1->Fun();
    27. pd1->Fun();
    28. return 0;
    29. }

    image.png