![](/img/trans.png)
[英]How can i call the parameterized constructor for all objects in my dynamic array of objects on allocation in c++?
[英]Dynamical allocation of array of objects using parameterized constructor C++
动态分配对象数组时出现问题。 我创建了一个简单的名为Rectangle的类
#include <iostream>
class Rectangle
{
public:
// parameterized constructor, providing the height and width of a rectangle
Rectangle(int height, int width) : m_height(height), m_width(width)
{
std::cout << "Create a new rectangle with parameter constructor \n";
}
~Rectangle()
{
std::cout << "delete object \n";
}
// calculate the area of the rectangle
double area() const
{
return m_height*m_width;
}
// print the information of the rectangle
friend std::ostream& operator<<(std::ostream &out, const Rectangle &rec)
{
out << "Rectangle " << rec.m_height << " x " << rec.m_width << " has area " << rec.area();
return out;
}
private:
double m_height;
double m_width;
};
然后在main函数中,定义一个由Rectangle类的3个对象组成的数组,并为每个对象指定高度和宽度。
int main()
{
Rectangle * rec1 = new Rectangle[3]{{ 10, 20 }, { 20, 30 }, { 40, 50 }};
for (int i = 0; i < 3; ++i)
std::cout << rec1[i] << '\n';
return 0;
}
但是,我收到了一个错误(来自VS2013),为错误1错误C1001:编译器发生内部错误。
但是如果我在类的定义中评论析构函数
/*~Rectangle()
{
std::cout << "delete object \n";
}*/
该程序可以运行,结果如下。
Create a new rectangle with parameter constructor
Create a new rectangle with parameter constructor
Create a new rectangle with parameter constructor
Rectangle 10 x 20 has area 200
Rectangle 20 x 30 has area 600
Rectangle 40 x 50 has area 2000
Press any key to continue . . .
我不知道这是什么问题。 通常,出于某些目的,我们应该在类中声明一个析构函数。 但是在这种情况下,它会产生错误。 我尝试在互联网上搜索问题,但找不到答案。
如果您收到内部编译器错误,则表明您的编译器已损坏。 升级或使用其他编译器。 细微的代码更改可以消除错误,但问题不是您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.