override
含义:被标识的函数需要强制重写基类虚函数。
class Base {
public:
Base() = default;
~Base() = default;
virtual void test() {}
};
class Derived : public Base {
public:
Derived() = default;
~Derived() = default;
virtual void teat() {}
};
// 原本想要在派生类重写test函数,但是因为手抖新建了一个teat函数,编译器并不会报错!
// 为了避免上述手抖得情况,在派生类需要重写的虚函数后面加上override关键字
class Base {
public:
Base() = default;
~Base() = default;
virtual void test() {}
};
class Derived : public Base {
public:
Derived() = default;
~Derived() = default;
// virtual void teat() override {} // 提示错误
virtual void test() override {}
};
final
含义:被标识的虚函数禁止被重写,或者禁止某个类被继承。
// final表示虚函数
class Base {
public:
Base() = default;
~Base() = default;
virtual void test() final {}
};
class Derived : public Base {
public:
Derived() = default;
~Derived() = default;
// virtual void test() {} // error
};
// final表示类
class Base final {
public:
Base() = default;
~Base() = default;
};
class Derived : public Base { // error Base不能被继承
public:
Derived() = default;
~Derived() = default;
};