C++ 带类的结构
C++ Struct with class
我正在尝试实现类矩形,它由代表矩形相对角的两个点组成。点结构已在头文件中声明。我不知道如何在矩形类的结构类中使用 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
结构添加构造函数。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++概念:如何使用'concept'检查模板化结构的属性?