I have a problem when dynamically allocating an array of objects. I have created a simple class named 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;
};
Then in the main function, I define an array of 3 objects of the Rectangle class and given the height and width for each object.
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;
}
However, I got an error (from VS2013) as Error 1 error C1001: An internal error has occurred in the compiler.
But if I comment the destructor in the definition of the class
/*~Rectangle()
{
std::cout << "delete object \n";
}*/
The program can run, and I got the result as follows.
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 . . .
I don't know what is the problem here. Normally, we should declare a destructor in the class for some purposes. But in this case, it produces an error. I try to search the problem on the internet but I failed to find out the answer.
If you get an internal compiler error, it means your compiler is broken. Either upgrade or use a different compiler. Subtle code changes can suppress the error, but it's not your code that's the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.