在 class 中使用析构函数

Using destructor in class

我有一个使用 classes(非常基本的元素)的 C++ 项目。 我的 class 看起来像这样:

class vehicule: public frane,public motor,public directie,public noxe,public caroserie
{
    char tip[40];
    int placfatacant,placfatatot;
    static const int placfatapret=18;
    int placspatecant,placspatetot;
    static const int placspatepret=15;
public:
    vehicule()
    void settip(char)
    void verifauto()
;};

有人告诉我必须使用复制构造函数和析构函数。我有一些例子,但都使用动态分配。现在我的问题 is:what 我的副本 constructor/destructor 应该做什么,因为我没有动态分配内存给 copy/delete?或者我应该将数据声明为

int *placfatacant

然后使用

delete placfatacant

? 提前致谢!

如你所说,如果你需要处理动态分配变量的删除,你只需要声明一个构造函数。一般来说,对于每个 new,必须有一个 delete.

我在您的 class 中没有看到任何 new 对象,所以我会让编译器生成的 destructor/copy 构造函数执行它的操作。您的 class 完全是静态分配的,当它超出使用它的上下文范围时将被删除。

如果是为了学校目的,你可以改变:

// From:
char tip[40];

// To:
char * tip;`

然后在你的构造函数中你将:

tip = new char[40]();

现在你必须像这样创建一个拷贝构造函数:

vehicule(const vehicule & toCopy)
{
    tip = new char[40]();
    strcpy(tip, toCopy.tip);
}

你的析构函数只需要解除分配 tip:

~vehicule()
{
    delete tip;
}