我不断收到来自编译器的错误消息,说存在内存泄漏、两个 8 字节块和一个 5 字节块。我已经删除*name
了析构函数中的数组。析构函数如何处理作用域?我的印象是,一旦主体结束,fruit
对象将在超出范围时被删除。
#include "Fruit.h"
#include "LeakWatcher.h"
using namespace std;
Fruit::Fruit(const Fruit &temp )
{
name = temp.name;
for(int i = 0; i < CODE_LEN - 1; i++)
{
code[i] = temp.code[i];
}
}
void Fruit::operator=(const Fruit &tempFruit)
{
name = tempFruit.name;
for(int i = 0; i < CODE_LEN; i++)
{
code[i] = tempFruit.code[i];
}
}
Fruit::~Fruit()
{
delete[] name;
}
bool Fruit::operator==(const Fruit &tempFruit)
{
int i = 0;
while(name[i] != NULL && tempFruit.name[i] != NULL)
{
if(name[i] != tempFruit.name[i])
return false;
i++;
}
if(name[i] != NULL || tempFruit.name[i] != NULL)
return false;
return true;
}
bool Fruit::operator<(const Fruit &tempFruit)
{
int i = 0;
while(name[i] != NULL && tempFruit.name[i] != NULL)
{
if((int)name[i] < (int)tempFruit.name[i])
return true;
else if((int)name[i] > (int)tempFruit.name[i])
return false;
i++;
}
if(name[i] == NULL && tempFruit.name[i] != NULL)
return true;
else
return false;
}
std::ostream & operator<<(std::ostream &os, const Fruit *printFruit)
{
os << setiosflags(ios::left) << setw(MAX_NAME_LEN) << printFruit->name << " ";
for(int i = 0; i < CODE_LEN; i++)
{
os << printFruit->code[i];
}
os << endl;
return os;
}
std::istream & operator>>(std::istream &is, Fruit *readFruit)
{
string tempString;
is >> tempString;
int size = tempString.length();
readFruit->name = new char[tempString.length()];
for(int i = 0; i <= (int)tempString.length(); i++)
{
readFruit->name[i] = tempString[i];
}
readFruit->name[(int)tempString.length()] = '\0';
for(int i =0; i < CODE_LEN; i++)
{
is >> readFruit->code[i];
}
return is;
}
void stuff()
{
}
void main()
{
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
Fruit *fruit = new Fruit();
Fruit *fruit1 = new Fruit();
cin >> fruit;
*fruit1 = *fruit;
cout << fruit << fruit1;
_CrtDumpMemoryLeaks();
}
H
#ifndef _FRUIT_H
#define _FRUIT_H
#include <cstring>
#include <sstream>
#include <iomanip>
#include <iostream>
enum { CODE_LEN = 4 };
enum { MAX_NAME_LEN = 30 };
class Fruit
{
private:
char *name;
char code[CODE_LEN];
public:
Fruit(const Fruit &temp);
Fruit(){name = NULL;};
bool operator<(const Fruit &other);
friend std::ostream & operator<<(std::ostream &os, const Fruit *printFruit);
bool operator==(const Fruit &other);
bool operator!=(const Fruit &other){return!(*this==other);};
friend std::istream & operator>>(std::istream& is, Fruit *readFruit);
void Fruit::operator=(const Fruit &tempFruit);
~Fruit();
};
#endif