override 字面意思为覆盖的
override 为C++11新增加的关键字,在C++11中 override 的作为为防止虚函数未被正确的调用,下面我们来看两段代码
1 | #include <iostream> |
在main函数中,我们声明定义了Base类指针 b 指向了Derived,然后通过b指针调用了 functionA函数,按照对虚函数的理解,我们程序执行完以后应该打印This is Derived::functionA",但实际程序执行完后打印的是This is Base::functionA,这是因为两个函数有不同的形参,Derived类中的functionA函数只不过是对基类的functionA的函数的重载,如果想要正确的调用Derived类中的函数,我们需要在函数后面加上override关键字,override 关键字告诉编译器,该函数应覆盖基类中的函数。如果该函数实际上没有覆盖任何函数,则会导致编译器错误。
#include <iostream>
#include <memory>
using namespace std;
class Base
{
public:
virtual void functionA(int arg) const {
cout << "This is Base::functionA" << endl;
}
};
class Derived : public Base
{
public:
// 注意 这里函数参数如果还是long 类型,编译器在编译的时候会报错
virtual void functionA(int arg) const override {
cout << "This is Derived::functionA" << endl;
}
};
int main()
{
// Base pointer b points to a Derived class object.
shared_ptr<Base>b = make_shared<Derived>();
// Call virtual functionA through Base pointer.
b->functionA(99);
return 0;
}
```override 字面意思为 覆盖的
override 为C++11新增加的关键字,在C++11中 override 的作为为防止虚函数未被正确的调用,下面我们来看两段代码
#include <iostream>
#include <memory>
using namespace std;
class Base
{
public:
virtual void functionA(int arg) const {
cout << "This is Base::functionA" << endl;
}
};
class Derived : public Base
{
public:
virtual void functionA(long arg) const {
cout << "This is Derived::functionA" << endl;
}
};
int main()
{
// Base pointer b points to a Derived class object.
shared_ptr<Base>b = make_shared<Derived>();
// Call virtual functionA through Base pointer.
b->functionA(99);
return 0;
}
在main函数中,我们声明定义了Base类指针 b 指向了Derived,然后通过b指针调用了 functionA函数,按照对虚函数的理解,我们程序执行完以后应该打印This is Derived::functionA",但实际程序执行完后打印的是This is Base::functionA,这是因为两个函数有不同的形参,Derived类中的functionA函数只不过是对基类的functionA的函数的重载,如果想要正确的调用Derived类中的函数,我们需要在函数后面加上override关键字,override 关键字告诉编译器,该函数应覆盖基类中的函数。如果该函数实际上没有覆盖任何函数,则会导致编译器错误。
#include <iostream>
#include <memory>
using namespace std;
class Base
{
public:
virtual void functionA(int arg) const {
cout << "This is Base::functionA" << endl;
}
};
class Derived : public Base
{
public:
// 注意 这里函数参数如果还是long 类型,编译器在编译的时候会报错
virtual void functionA(int arg) const override {
cout << "This is Derived::functionA" << endl;
}
};
int main()
{
// Base pointer b points to a Derived class object.
shared_ptr<Base>b = make_shared<Derived>();
// Call virtual functionA through Base pointer.
b->functionA(99);
return 0;
}