具有三个构造函数的矩形类
Rectangle class with three constructors
我需要完成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)。在存储float
s时,实际上不需要复制构造函数或析构函数。如果你坚持存储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);
}
相关文章:
- c++ 构造函数 将 1 个字符串参数转换为 3 个属性
- 两个父类的构造函数的序列
- 使第二个类的构造函数成为第一个类中的友元函数
- 关于 std::bitset 构造函数的几个问题?
- 有一个构造函数,但有两个析构函数
- C++ 关于两个类构造函数的问题
- 重载具有 2 个相同数据类型成员的构造函数
- 为什么 getch 在按下函数或箭头键时返回三个值?
- 候选构造函数(隐式复制构造函数)不可行:第一个参数需要 l 值
- 用相同的参数声明两个构造函数的最偶像化的方法是什么?
- 如何在构造函数初始值设定项列表中使用 n 个元素初始化 std::vector<std::time_t>
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C++使用函数对象的线程,如何调用多个析构函数而不是构造函数?
- 如何使用三个参数化构造函数的rand()函数初始化对象的数组
- 具有三个构造函数的矩形类
- 这三个构造函数的区别是什么?
- 为什么析构函数构造的两个对象被调用三次
- Std::set构造函数第二个参数错误
- 关于 std::variant 中三个构造函数的问题
- 模板大小递归--构造函数多个重载