向前声明和删除

Forward declaration and delete

本文关键字:删除 声明      更新时间:2023-10-16

老师让我做期末作业。我需要在c++中列出一个清单(不能使用boost, STL等)。我的Stuff类必须在List类之后定义。我试过的小例子:

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class Stuff;
class List
{
    private :
        Stuff *s;
        int n;
    public :
        List(int n)
        {
            this->n = n;
            s = new Stuff[n];
        }
        ~List()
        {
            delete[] s;
            s = NULL;
            n = 0;
        }
};
class Stuff
{
    private :
        string name;
        double price;
    public :
        Stuff(){}
};
int main(int argc, char **argv)
{
    return 0;
}

我知道,那:

"如果被删除的对象在点具有不完整的类类型删除和完整类具有非平凡析构函数或函数,其行为未定义。"

那我该怎么做呢?什么好主意吗?记住,我不能使用boost、STL等。AND Stuff类必须在List类之后定义。

要使这段代码工作,需要在定义List类的构造函数和析构函数之前定义Stuff

:

class Stuff;
class List
{
    private :
        Stuff *s;
        int n;
    public :
        List(int n);
        ~List();
};
class Stuff
{
    private :
        string name;
        double price;
    public :
        Stuff(){}
};
List::~List()
{
    delete[] s;
    s = NULL;
    n = 0;
}
List::List(int n)
{
    this->n = n;
    s = new Stuff[n];
}

模板呢?

template<class T>
class List
{
private :
    T *s;
    int n;
public :
    List(int n)
    {
        this->n = n;
        s = new T[n];
    }
    ~List()
    {
        delete[] s;
        s = NULL;
        n = 0;
    }
};
class Stuff
{
private :
    string name;
    double price;
public :
    Stuff(){}
    ~Stuff(){}
};

int main(int argc, char **argv)
{
    List<Stuff> list(4);
    return 0;
}

您必须将List声明放在头文件中,并将实现放入源文件中,其中Stuff定义可用(#include "Stuff.h"),您可以删除Stuff

或者您可以在同一文件中实现List,但是在Stuff声明之后,这样编译器实际上知道要删除

将声明与实现分开。虽然你不能使用boost等,但你可以使用单独的头文件和源文件。

List类的定义放入in列表中。在stuff.hh中Stuff类的定义。在类List的定义中(在list.hh中),声明但不定义那些需要知道类Stuff的成员函数。将这些函数定义放入源文件list.cpp中。这个源文件将#包括这两个列表。

您将class Stuff;替换为实际实现的代码。class Stuff;是一个前向声明,这意味着你可以引用class Stuff,但你不能使用它。

这里有两个解决方案:


class Stuff {
private :
    string name;
    double price;
public :
    Stuff(){}
};
class List
{
private :
    Stuff *s;
    int n;
public :
    List(int n) {
        this->n = n;
        s = new Stuff[n];
    }
    ~List() {
        delete[] s;
        s = NULL;
        n = 0;
    }
};

class Stuff;
class List
{
private :
    Stuff *s;
    int n;
public :
    List(int n);
    ~List();
}
class Stuff {
private :
    string name;
    double price;
public :
    Stuff(){}
};
List::List(int n) {
    this->n = n;
    s = new Stuff[n];
}
List::~List() {
    delete[] s;
    s = NULL;
    n = 0;
}