c++ - 区分 C++ 中基指针 vector 中的派生对象

标签 c++ inheritance derived-class

跟进这个问题 Vector/Container comprised of different derived objects in C++我试图改进我的代码。现在我将指向派生对象的指针存储在单个 vector 中,但我不确定然后如何访问它们的派生类特定成员函数将单个 vector 拆分为子 vector 每个派生类型。

#include <vector>
#include <memory> // for unique_ptr
#include <iostream>

using namespace std;

class Fruit {};
class Banana: public Fruit { void cout_banana() { cout << "i am a banana" << endl; } };
class Apple : public Fruit { void cout_apple() { cout << "i am an apple" << endl; } };

class FruitBox
{
    vector<unique_ptr<Banana>> vec_banana;
    vector<unique_ptr<Apple>>  vec_apple;

public:
    FruitBox(const vector<unique_ptr<Fruit>> &fruits)
    {
        for (const unique_ptr<Fruit> &f : fruits)
        {
            // How to figure out if f is Banana or Apple and then
            // 1) Print either cout_banana or cout_apple
            // 2) Store/Move f in either vec_banana or vec_apple
        }
    }
};

void main()
{
    vector<unique_ptr<Fruit>> inputs;
    inputs.emplace_back(new Banana());
    inputs.emplace_back(new Apple());

    FruitBox fbox = FruitBox(inputs);
}

最佳答案

我认为您的问题不在于实现本身(可以使用 dynamic_cast 检查实际的类,但我不会在这里深入探讨,因为这是不必要的),而是您的理解首先是面向对象 - 至少在这个特定的例子中。

Liskov Substitution Principle声明 “如果 S 是 T 的子类型,则类型 T 的对象可以替换为类型 S 的对象(即类型 T 的对象可以替换为子类型 S 的任何对象)。” 这里不是这种情况。

与其在子类中定义 cout_xyz,不如将 void cout_fruit() 编写为 class Fruit 中的抽象方法,并在子类。

class Fruit { public: virtual void cout_fruit() = 0; };
class Banana: public Fruit { public: void cout_fruit() override { cout << "i am a banana" << endl; } };
class Apple : public Fruit { public: void cout_fruit() override { cout << "i am an apple" << endl; } };
// [...]

然后,对于每个水果,您只需调用 f->cout_fruit()

关于c++ - 区分 C++ 中基指针 vector 中的派生对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50463247/

相关文章:

C++ 将一个对象传递给另一个对象?

ruby - Swift 实例 vs 类方法加上类继承

javascript - 来自 sub 时直接调用其他 super 方法

c++ - 派生类中指向基类的指针 vector

C++在派生类中初始化基类的const int?

c++ - Boost 中的关键字列表运算符

c++ - QString 从行首或行尾修剪非空白字符

c++ - 将 vector 映射的选择性元素减少为 vector

c++ - CRTP 派生类在使用继承的赋值运算符后丢失其成员和段错误?

python - 对 argparse 参数解析器进行子类化