c++ - 派生类的成员函数行为能否由其实例化的类决定?

标签 c++ inheritance virtual-inheritance

Rectangle 和 Triangle 类都派生自 Shape。我想添加另一个类 ComplexShape,它可以是任何特定的形状并附加其他形状。

我知道这个问题有一些简单的解决方法,比如在基类中声明一个变量来存储形状属性,但我对解决标题问题的方法更感兴趣。如果可能,我该如何定义 ComplexShape 的构造函数,以便 ComplexShape 使用用于初始化它的类的方法?

#include <iostream>
#include <memory>
#include <vector>

class Shape {
    public: virtual unsigned int getPointCount() const = 0;
};

class Rectangle : public Shape {
    public: unsigned int getPointCount() const { return 4; }
};

class Triangle : public Shape {
    public: unsigned int getPointCount() const { return 3; }
};

class ComplexShape : public Shape {
public:
    std::vector<std::shared_ptr<Shape>> children;

    //What Constructor comes here?

    unsigned int getPointCount() const {
        unsigned int i{ 0u };
        for(auto shape : children) i += shape->getPointCount();
        return i;
    }
};

int main() {
    Triangle triangle();
    ComplexShape arrow; //How do I initialize this as a rectangle?
    arrow.children.push_back(std::shared_ptr<Shape>(new Triangle()));
    std::cout << arrow.getPointCount();
    return 0;
};

最佳答案

您可以尝试使用构造函数中使用的初始化列表:http://www.cplusplus.com/reference/initializer_list/initializer_list/

#include <iostream>
#include <memory>
#include <vector>
#include <initializer_list>

class Shape {
public: virtual unsigned int getPointCount() const = 0;
};

class Rectangle : public Shape {
public: unsigned int getPointCount() const { return 4; }
};

class Triangle : public Shape {
public: unsigned int getPointCount() const { return 3; }
};

class ComplexShape : public Shape {
public:
    std::vector<std::shared_ptr<Shape>> children;
    ComplexShape() {}

    ComplexShape(std::initializer_list<std::shared_ptr<Shape>> init) : children(init)
    {
        // do some dynamic_cast magic here
    }

    unsigned int getPointCount() const {
        unsigned int i{ 0u };
        for (auto shape : children) i += shape->getPointCount();
        return i;
    }
};

int main() {
    Triangle triangle();
    ComplexShape arrow; //How do I initialize this as a rectangle?
    arrow.children.push_back(std::shared_ptr<Shape>(new Triangle()));
    std::cout << arrow.getPointCount();

    // This could be simplified probably
    ComplexShape rect = { std::shared_ptr<Shape>(new Triangle()), std::shared_ptr<Shape>(new Triangle()) };
    return 0;
};

关于c++ - 派生类的成员函数行为能否由其实例化的类决定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45632329/

相关文章:

c++ - Cppreference 的复杂性?

c++ - 获取指针的地址并为其赋值

objective-c - 如果两个 ObjC 类别重写同一个方法会怎样?

java - 为什么不能从父类中实现的接口(interface)对象调用子类方法

c++ - cpp继承虚方法解析顺序

c++ - 纯虚拟类和集合( vector ?)

c++ - 如何更改任务管理器中的应用程序图标

c++ - 从 C 代码调用共享库加载器

java - 为什么Java不允许我通过同一个类的方法访问私有(private)方法?

c++ - 调用非虚拟基方法时,C++ 中的虚拟继承是否有任何惩罚/成本?