所以..我一直在努力释放一个数组。
我不知道为什么会有内存泄漏,但不知何故有一个。
除了主函数之外,我没有在任何地方分配任何内存。
#include <iostream>
#include "Motorboat.h"
#include "Sailboat.h"
using namespace std;
void printSailBoats(Boat* arr[], int nrOfElements);
int main() {
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // used to check for memoryleaks in debug mode
Boat* test[4];
int nrOfElements = 4;
test[0] = new Motorboat("heeelllooo",15000,"v100");
test[1] = new Sailboat("saaailboat",1004,43.5);
test[2] = new Motorboat("ASDK",4932,"Blabla");
test[3] = new Sailboat("DKEOK",4992,103.4);
printSailBoats(test,nrOfElements);
for(int i=0; i<4; i++) {
delete test[i];
}
return 0;
}
void printSailBoats(Boat* arr[], int nrOfElements) {
// prints all sailboats
}
编辑:添加了课程。 船.h:
#ifndef BOAT_H
#define BOAT_H
#include <string>
using namespace std;
class Boat {
public:
virtual void setModel(string newModel) = 0;
virtual void setPrice(int newPrice) = 0;
virtual string getModel() const = 0;
virtual int getPrice() const = 0;
virtual string getType() const = 0;
virtual string toString() const = 0;
};
#endif
帆船.h:
#ifndef SAILBOAT_H
#define SAILBOAT_H
#include "Boat.h"
class Sailboat: public Boat {
private:
double sailArea;
string model;
int price;
public:
Sailboat(string model, int price, double sailArea);
void setSailArea(double newSailArea);
double getSailArea() const;
string toString() const;
void setModel(string newModel);
void setPrice(int newPrice);
string getModel() const;
int getPrice() const;
string getType() const;
};
#endif
帆船.cpp:
#include "Sailboat.h"
Sailboat::Sailboat(string model, int price, double sailArea) {
this->model = model;
this->price = price;
this->sailArea = sailArea;
}
// Setters, getters and toString...
对于 motorboat 类来说,这几乎是一样的,只是有一个字符串变量来存储引擎的名称而不是saiarea。