gpt4 book ai didi

c++ - 转发声明和删除

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:22:33 25 4
gpt4 key购买 nike

我的老师让我做期末作业。我需要用 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;
}

我知道,那:

"If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined."

但是我该怎么做呢?有任何想法吗?请记住,我不能使用 boost、STL 等。并且 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];
}

关于c++ - 转发声明和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16614807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com