1.概要
c++11 新特性 override 检查函数不可以被重写
2.代码
#include <iostream>
using namespace std;
namespace T1 {
class A
{
public:
virtual void fun() {
cout << "a fun \n";
}
};
class A1 :A
{
public:
void fun() override {
cout << "a1 fun \n";
}
};
void test() {
cout << "test1-----------------------\n";
A* a = (A*)new A1();
a->fun();
}
}
namespace T2 {
class A
{
public:
void fun() {
cout << "a fun \n";
}
};
class A1 :A
{
public:
/* override: It is not a virtual function that cannot be overwritten
void fun() override {
cout << "a1 fun \n";
}
*/
};
void test() {
cout << "test1----------override: It is not a virtual function that cannot be overwritten-------------\n";
A* a = (A*)new A1();
a->fun();
}
}
int main()
{
T1::test();
T2::test();
std::cout << "Hello World!\n";
}
2.运行结果
test1-----------------------
a1 fun
test1----------override: It is not a virtual function that cannot be overwritten-------------
a fun
Hello World!
文章探讨了C++中`override`关键字的用法,指出在重写虚函数时,只有声明为virtual的函数才能被override。在T1和T2的示例中,T1中的A1::fun可以被override,但在T2中由于fun函数未声明为virtual,编译器会报错。
1万+

被折叠的 条评论
为什么被折叠?



