C++11中的override关键字

2023/10 19 21:10

一句话总结: 没什么用

用来显式指示子类virtual函数是override的, 加了可读性更好, 不加一样跑

加错了,编译器报错; 这样父类删了virtual函数时,子类编译就报错了.

#include <stdio.h>

class ClassA
{
public:
    virtual void Hello()
    {
        printf("ClassA.Hello\n");
    }
    void World()
    {
        printf("ClassA.World\n");
    }
};

class ClassB : public ClassA
{
public:
    virtual void Hello() // override - recommend syntax
    {
        printf("ClassB.Hello\n");
    }
    void World() // override - compile error
    {
        printf("ClassB.World\n");
    }
};

int main()
{
    ClassB* b = new ClassB();
    ClassA* a = b;

    a->Hello();
    a->World();

    b->Hello();
    b->World();

    return 0;
}

关于虚表尾巴的空间占用问题,以下代码可以指证

在32位系统下, 有虚表的为4(32字节), 无虚表的为1(4字节)

#include <stdio.h>

class ClassA
{
public:
    virtual void Hello()
    {
        printf("ClassA.Hello\n");
    }
    void World()
    {
        printf("ClassA.World\n");
    }
};

class ClassB : public ClassA
{
public:
    virtual void Hello() // override - recommend syntax
    {
        printf("ClassB.Hello\n");
    }
    void World() // override - compile error
    {
        printf("ClassB.World\n");
    }
};

class ClassC
{
public:
    void World()
    {
        printf("ClassC.World\n");
    }
};

int main()
{
    ClassB* b = new ClassB();
    unsigned int add1 = (unsigned int)(b);
    b++;
    unsigned int size1 = (unsigned int)(b) - add1;

    ClassC* c = new ClassC();
    add1 = (unsigned int)(c);
    c++;
    unsigned int size2 = (unsigned int)(c)- add1;

    printf("%d, %d\n", size1, size2);

    return 0;
}