c++覆盖基类的功能

标签 c++

我对 C++ 中的面向对象编程还很陌生,我找不到以下问题的解决方案,我希望这甚至是可能的。

我有 3 个类:BaseChildChild2

他们都得到了函数talk();

我想将BaseChildChild2 对象存储在一个数组中,并遍历它们并执行它们的talk( ) 函数。

这是我希望他们打印的内容:

- Base: "base"
- Child: "child"
- Child2: "child2"

这是我的类(class):

class Base {
public:
    virtual void talk() {
        printf("base\n");
    }
}

class Child : public Base {
public:
    using Base:draw;
    void talk() {
        printf("child\n");
    }
}

class Child2 : public Base {
public:
    using Base:draw;
    void talk() {
        printf("child2\n");
    }
}

这是我的数组:

Base objects[3];
objects[0] = Base();
objects[1] = Child();
objects[2] = Child2();

for(int i = 0; i < 3; i++) {
    objects[i]->talk();
}

输出应该是:

base
child
child2

最佳答案

您的代码正在切片对象。当您将基类的变量分配给派生类的值时,您最终会得到一个基对象。此时,原来的派生类什么都没有了,只有一个基类。

在 C++ 中,多态 处理对象的方法(即保留原始类型的信息)是使用引用或指针。但是,您不能将引用放入数组中。

这意味着,您需要一组指针 - 但不是原始指针。您需要所谓的智能指针。综合起来,您的代码应该是这样的:

std::unique_ptr<Base> objects[3] = {new Base(), new Child(), new Child2()};

for(int i = 0; i < 3; i++) {
    objects[i]->talk();
}

关于c++覆盖基类的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35017647/

相关文章:

c++ - 从 CIImage 创建垫子的最佳方法?

c++ - 通过函数越来越深入地传递指针

c++ - `std::memory_order_acquire` 的语义是否需要 x86/x86_64 上的处理器指令?

c++ - 我无法使用 C++ 使用 MPI 编译器进行编译

c++ - 实时视频流的 GOP 大小

java - C++和Java编译过程的区别

c++ - 我该怎么办 : convert surface to a texture or create a texture with certain multisampling parameters or render a surface with an alpha layer

C++ 类的不变性和优点/缺点

c++ - 如何从 OpenGL 中的纹理中删除黑色背景

c++ - 使这个 UDP 监听套接字成为非阻塞的,我是否有可能搬起石头砸自己的脚?