首页 > 解决方案 > 我可以在初始化派生类时构造基类来分配吗?

问题描述

我正在做这个程序任务。所以我不能改变头文件。这意味着我不能制作 get() 或 set() 函数。

下面的代码是我正在使用的基类的标题

#include "IShape.h"
#include <vector>

class Polygon : public IShape {
private:
    std::vector<Point> points;
public:
    Polygon() = default;
    Polygon(const Point& one, const Point& two, const Point& three);
    Polygon(const std::vector<Point>& points);
    Polygon(const Polygon& polygon);
    virtual ~Polygon() {
      std::cout << "Polygon is destructed!" << std::endl;
    };

    virtual bool contain(Point p) const override;
    virtual double getPerimeter() const override;
    virtual double getArea() const override;

    //https://en.cppreference.com/w/cpp/language/virtual - covariant return types
    //Since the return value is a pointer or reference to a derived class (child class) of IShape,
    //the clone() function can be overridden
    virtual Polygon* clone() const override {
        return new Polygon(*this);
    };

protected:
    virtual std::ostream& toString(std::ostream& os) const override;
};

IShape 是 Ishape 的基类,由纯虚函数组成。

问题在下面。

#include "Polygon.h"

class Rectangle final : public Polygon {
private:
    std::ostream &toString(std::ostream &os) const override;
public:
    Rectangle() = default;
    Rectangle(Point p1, Point p2, Point p3, Point p4);
    Rectangle(const std::vector<Point> points) : Polygon(points) {};
    virtual ~Rectangle() {
      std::cout << "Rectangle is destructed!" << std::endl;
    }

    double getPerimeter() const override;
    double getArea() const override;
    Rectangle *clone() const override;
    bool contain(Point p) const override;

};

我想问的是,当我初始化 using 时Rectangle(Point p1, Point p2, Point p3, Point p4),我需要制作在 Polygon 类中声明的向量。

鉴于它是成员变量,我不能直接更改它,并且我不能使用初始化列表,因为向量没有转移到它。

Rectangle::Rectangle(Point p1, Point p2, Point p3, Point p4)
{
    vector<Point> temp_vec;
    temp_vec.push_back(p2);
    temp_vec.push_back(p1);
    temp_vec.push_back(p3);
    temp_vec.push_back(p4);
    Polygon(temp_vec);
}

上面的代码是我的想法。但是编译器说error: conflicting declaration 'Polygon temp_vec'

你能给我什么建议吗?谢谢

标签: c++vectorconstructor

解决方案


创建一个static辅助函数 make temp_vec,如下所示:

static std::vector<Point> get_temp_vec(Point p1, Point p2, Point p3, Point p4) {
    std::vector<Point> temp_vec;
    temp_vec.push_back(p2);
    temp_vec.push_back(p1);
    temp_vec.push_back(p3);
    temp_vec.push_back(p4);
    return temp_vec;
}

然后让你的构造函数像这样使用它:

Rectangle::Rectangle(Point p1, Point p2, Point p3, Point p4) : Polygon(get_temp_vec(p1, p2, p3, p4)) {}

另外,我不确定“我不能使用初始化列表,因为向量没有传输到它”是什么意思,但是当我尝试它时它工作正常:

Rectangle::Rectangle(Point p1, Point p2, Point p3, Point p4) : Polygon(std::vector<Point>{p2, p1, p3, p4}) {}

不过,上述技术在其他不起作用的情况下仍然有用。


推荐阅读