当我分配几乎相同的类但有一个成员变量为字符串而不是整数时,我有内存泄漏的问题.
带有字符串的类会产生内存泄漏,但不会产生整数.我删除了我可以删除的所有内容,但我仍然得到内存泄漏请帮忙.
所以soundbook类给我内存泄漏我不知道为什么因为我已经分配任何东西,但当我删除字符串成员我不再得到内存泄漏为什么会发生这种情况?
//主要
#include <iostream>
#include "PappersBok.h"
#include "SoundBook.h"
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
Books *bk[5];
bk[0] = new SoundBook();
bk[1] = new PappersBok();
bk[2] = new PappersBok();
bk[3] = new PappersBok();
bk[4] = new PappersBok();
for (int i = 0; i < 5; i++)
{
delete bk[i];
}
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
// soundbook类.h和.cpp
#ifndef SOUNDBOOK_H
#define SOUNDBOOK_H
#include "books.h"
class SoundBook : public Books
{
private:
std::string medium;
public:
SoundBook(std::string title = "?", std::string author = "?", std::string medium = "?");
~SoundBook();
std::string toString() const;
void setMedium(std::string medium);
};
#endif
//.cpp
#include "SoundBook.h"
SoundBook::SoundBook(std::string title, std::string author, std::string medium)
:Books(title, author)
{
this->medium = medium;
}
SoundBook::~SoundBook()
{
}
std::string SoundBook::toString() const
{
return ", Medium: " + this->medium;
}
Run Code Online (Sandbox Code Playgroud)
// Pappersbok class .cpp和.h
#ifndef PAPPERSBOK_H
#define PAPPERSBOK_H
#include "books.h"
class PappersBok : public Books
{
private:
int nrOfPages;
public:
PappersBok(std::string title = "?", std::string author = "?", int nrOfPages = 0);
~PappersBok();
std::string toString() const;
};
#endif
Run Code Online (Sandbox Code Playgroud)
//.cpp
#include "PappersBok.h"
PappersBok::PappersBok(std::string title, std::string author, int nrOfPages)
:Books(title, author)
{
this->nrOfPages = nrOfPages;
}
PappersBok::~PappersBok()
{
}
std::string PappersBok::toString() const
{
return ", Number of pages: " + std::to_string(this->nrOfPages);
}
Run Code Online (Sandbox Code Playgroud)