向前声明和删除
Forward declaration and delete
老师让我做期末作业。我需要在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;
}
相关文章:
- 删除显式默认函数声明时的警告
- 删除在结构 c++ 中声明的数组元素
- 如果未声明,则由预处理器删除thread::hardware_concurrency
- 未定义与已删除与未声明的函数
- 模板函数可以使用带有删除的构造函数的声明类型
- 定义或声明类破坏者时,C 使用已删除的函数
- 删除堆栈上声明的对象
- 为什么当我使用"new"关键字声明数组指针时无法删除它
- 当指定初始化程序的顺序和字段声明不一致时,clang可以删除函数调用
- 拆分函数的声明和定义,还是删除标头中的新运算符?
- 析构函数删除在 main 中声明的动态数组
- C :删除在堆栈上声明的结构的字段
- 结构sqlite3的sqlite3c++正向声明导致析构函数中删除时出现无效指针错误
- 为什么move构造函数既没有声明也没有用clang删除
- 为什么简单析构函数在使用基指针声明时不删除派生对象
- 如果我们只定义复制构造函数/oper=,为什么移动构造函数/move赋值没有隐式声明和定义为删除
- 我可以在可能的SDK中删除标头中的私有声明吗
- 错误:在此处声明unique_ptr(常量 unique_ptr&) = 删除;
- 为什么在声明移动分配时不删除复制分配
- boost::shared_ptr::shared_ptr(const boost::shared_ptr&)' 被隐式声明为已删除