C++ 带类的结构

C++ Struct with class

本文关键字:结构 C++      更新时间:2023-10-16

我正在尝试实现类矩形,它由代表矩形相对角的两个点组成。点结构已在头文件中声明。我不知道如何在矩形类的结构类中使用 x,y。

这是 .h 文件:

struct Point {
    double x, y;
};
// Define your class below this line
class Rectangle
{
public:
    Rectangle(double p.x, double p.y, double w, double h);
    double getArea() const;
    double getWidth() const;
    double getHeight() const;
    double getX() const;
    double getY() const;
    void setLocation(double x, double y);
    void setHeight(double w, double h);
private:
    Point p;
    double width;
    double height;
};

在.cpp中,我初始化如下:

Rectangle::Rectangle(double p.x, double p.y, double w, double h)
:(p.x),(p.y), width(w), height(h)
{
}

你可以像这样为点创建一个构造函数:

struct Point {
    double x, y;
    Point(double xx, double yy): x(xx), y(yy){}
};

然后将矩形中的构造函数更改为:

Rectangle::Rectangle(double x, double y, double w, double h)
:p(x,y), width(w), height(h)
{   
}

如果您使用的是 c++11,您还有一个额外的选项。因为Point是一个聚合结构,所以你可以按照 juanchopanza 的建议对其进行初始化,如下所示:

Rectangle::Rectangle(double x, double y, double w, double h)
:p{x,y}, width(w), height(h)
{   
}

这样做的好处是,如果选择此方法,则无需向Point结构添加构造函数。