Memory 类中的内存分配和删除 内存分配和指针有问题
我的指针和动态内存有问题。我制作了一个类FileReader,它从如下格式的文件中读取 名字、姓氏、年份、GPA 字符串,字符串,字符串,整数 克里斯,奈特,Fr,3.8 小米奇·泰勒,3.5 第一行,我将它存储在一个名为Names的向量中 向量中的第二行称为类型 我还创建了一个向量,它可以保存void指针,因为它可以保存任意类型 我的问题是,如何释放堆中的内存Memory 类中的内存分配和删除 内存分配和指针有问题,memory,copy,copy-constructor,void-pointers,dynamic-memory-allocation,Memory,Copy,Copy Constructor,Void Pointers,Dynamic Memory Allocation,我的指针和动态内存有问题。我制作了一个类FileReader,它从如下格式的文件中读取 名字、姓氏、年份、GPA 字符串,字符串,字符串,整数 克里斯,奈特,Fr,3.8 小米奇·泰勒,3.5 第一行,我将它存储在一个名为Names的向量中 向量中的第二行称为类型 我还创建了一个向量,它可以保存void指针,因为它可以保存任意类型 我的问题是,如何释放堆中的内存 #ifndef RECORD_H #define RECORD_H class Record{ private: //POIN
#ifndef RECORD_H
#define RECORD_H
class Record{
private:
//POINTER VARIABLES
int *intPtr;
double *doublePtr;
vector<string*> stringPtrList;
//NAMES,TYPES, AND VALUES
vector<string> Names;
vector<string> Types;
vector<void*> Values;
public:
Record(vector<string> _names, vector<string> _types, vector<string>_values){
Names = _names;
Types = _types;
//ALOCATING MEMORY
for (unsigned i = 0; i < Types.size(); i++){
string *stringPtr = new string;
stringPtrList.push_back(stringPtr);
}
for (unsigned int i = 0; i < Types.size(); i++){
if (Types[i] == "Integer"){
intPtr = new int;
*intPtr = stoi(_values[i]);
Values.push_back((void*)intPtr);
}
else if (Types[i] == "Double"){
doublePtr = new double;
*doublePtr = stod(_values[i]);
Values.push_back((void*)doublePtr);
}
else if (Types[i] == "String"){
*stringPtrList[i] = _values[i];
Values.push_back((void*)stringPtrList[i]);
}
else{
cout << "No match Type" << endl;
}
}
}
Record(const Record &r){
int *intPtr = new int;
intPtr = r.intPtr;
double *doublePtr = new double;
doublePtr = r.doublePtr;
for (int i = 0; i < r.stringPtrList.size(); i++){
stringPtrList[i] = new string;
stringPtrList[i] = r.stringPtrList[i];
}
}
~Record(){
delete intPtr, doublePtr;
for (int i = 0; i < Types.size(); i++){
delete stringPtrList[i];
}
cout << "Pointer are deleted" << endl;
}
friend ostream&operator <<(ostream &os, const Record &r){
for (unsigned int i = 0; i < r.Types.size(); i++){
if (r.Types[i] == "Integer"){
os << "Integer: " << *(int*)r.Values[i] << endl;
}
else if (r.Types[i] == "String"){
os << "String" << *static_cast<string*>(r.Values[i]) << endl;
}
else if (r.Types[i] == "Double"){
os << "Double" << *(double*)r.Values[i] << endl;
}
else{
cout << "Fatal Error!" << endl;
}
}
cin.get();
return os;
}
};
#endif
\ifndef记录
#定义记录
课堂记录{
私人:
//指针变量
int*intPtr;
双*双PTR;
向量字符串列表;
//名称、类型和值
载体名称;
媒介类型;
向量值;
公众:
记录(向量名称、向量类型、向量值){
名称=_名称;
类型=_类型;
//动态存储器
for(无符号i=0;iGPA必须是浮点,而不是整数。3.5不能是整数
这听起来像是一个家庭作业问题。即使不是这样,听起来也太复杂了。只需使用结构列表(向量)
如果您真的必须能够处理任何类型,只需使用stuct的值对类型,如下所示:
结构记录
{
字符串值;
VAR_TYPE;//这是您定义的某个枚举。
}
保留一个包含类型和列索引的列列表,以便在读取记录时轻松处理每个记录。
因为您知道每个记录的类型,所以可以在实际使用时将其转换为该类型
<>这是非常干净的,不需要动态分配(这是慢的),并且用空洞指针来处理。是C++还是别的什么?