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/