具有三个构造函数的矩形类

Rectangle class with three constructors

本文关键字:构造函数 三个      更新时间:2023-10-16

我需要完成Rectangle类。编写3个构造函数和一个析构函数来满足下面的main()。为每个构造函数使用构造函数初始值设定项。这就是所做的:

   class Rectangle
    {
       float* length;
       float* width;
    ...
    ???
    ...
    };

    int main()
    {
       Rectangle r1;
       Rectangle r2(4.5,2.3);
       Rectangle r3(r2);
    }

这就是我填充矩形类的方式:

class rectangle
{
  private:
   float* length;
   float* width;
  public:
    rectangle();                    //default constructor
    rectangle(double w, double l);  //constructor with parameters
    rectangle(const rectangle&);    //copy constructor
    ~rectangle(void);
    double getWidth(void);
    double getLength(void);
    double perimeter(void) const;
    double area(void) const;
};
    ...........
    ...........
    ...........
int main()
{
   rectangle r1;
   rectangle r2(4.5,2.3);
   rectangle r3(r2);
   //statements
}

我只是想知道我做的是对是错。有人能看到我是否缺少smth或需要添加到rectanglr类吗?!

我认为你做错了,因为的定义

Rectangle r2(4.5,2.3);

没有相应的构造函数。还要考虑到赋值中的类命名为矩形而不是矩形。:)

我认为应该定义四个数据成员来表示矩形的四个点,而不是长度和宽度(为什么要将它们声明为指针?!)。

三个构造函数(默认构造函数、自定义构造函数和复制构造函数)的声明和使用看起来是合理的。然而,存储指向float的指针看起来并不合理:您应该只存储float s(我实际上会存储double s,除非我有理由假设有大量的rectangle s)。在存储floats时,实际上不需要复制构造函数或析构函数。如果你坚持存储float*,从而分配内存,你还应该实现一个副本分配:

rectangle& rectangle::operator= (rectangle other) {
    other.swap(*this);
    return *this;
}
void rectangle::swap(rectangle& other) {
    std::swap(this->length, other.length);
    std::swap(this->width,  other.width);
}