首页 > 解决方案 > 制作数组时调用了太多次析构函数

问题描述

我是编程和学习课程的新手。我有一个类 Product 并试图创建一个产品数组,但是我的析构函数为两个对象调用了 3 次,它触发了一个断点。这是一些代码:

`

    class Product {
    private:
        char* name;
        int price;

    public:
        Product();
        Product(const char*, int);
        ~Product();

    };
    `

        Product::Product(const char* name, int price) {
        this->name = new char[strlen(name) + 1];
        strcpy(this->name, name);

        this->price = price;
    }



    Product::~Product() {
    delete[] this->name;
}

    int main() {

    Product redPaint("Red Paint", 25);
    Product bluePaint("Blue Paint", 26);
    Product paint[2] = { redPaint, bluePaint};
}

标签: c++oopdestructor

解决方案


推荐阅读