我收到"调试错误" CRT检测到应用程序在堆结束后写入内存。但我不明白为什么,也找不到类似的例子。
完整的代码是...... 虽然我认为这可能只是主要问题。
#include <iostream>
#include <cmath>
#include <array>
using namespace std;
// Declare global consts
const double pi = 3.1415926583;
// Base class Shape
class Shape{
protected:
double *sides;
public:
Shape(const int n){ //parameterized for n dimensional shape
sides = new double[n];
}
// need virtual destructor
virtual ~Shape(){
delete[] sides;
}
virtual double area() const = 0; // pure virtual function for area
virtual double volume() const = 0; // pure virtual function for volume
};
//////////////////////////////////////////////////////////
//Derived classes for 2D and 3D Shapes
class Shape2D : public Shape{ // inherit shape
protected:
int n = 2; //n denotes the number of dimensions
public:
// default constructor
Shape2D() :Shape(n){}
// param constructor
Shape2D(const double side1, const double side2) :Shape(n){
sides[0] = side1; sides[1] = side2;
}
virtual ~Shape2D(){} //virtual destructor
double volume() const { cout << "trying to calculate volume of 2d shape..." << endl; return 0; };
};
/////////////////////////////////////////////////////////////////////
//2D shapes
class Rectangle : public Shape2D{
public:
// constructors
Rectangle() :Shape2D() {}
Rectangle(const double side1, const double side2) :Shape2D(side1, side2){}
~Rectangle(){}
double area() const { return (sides[0] * sides[1]); }
};
int main(){
Shape **ShapePointer = new Shape*[2];
ShapePointer[0] = new Rectangle(2, 5);
ShapePointer[1] = new Rectangle(1, 3);
// clean up
delete ShapePointer[0];
delete ShapePointer[1];
delete[] ShapePointer;
system("pause");
return 0;
}
答案 0 :(得分:4)
危险!!!
protected:
int n = 2; //n denotes the number of dimensions
public:
// default constructor
Shape2D() :Shape(n){}
初始化n
时, Shape(n)
未定义
与
相同的问题Shape2D(const double side1, const double side2) :Shape(n)
如果可以,请将n
定义为static const
(或static constexpr
,因为您标记了C ++ 11)
protected:
static constexpr int n = 2; //n denotes the number of dimensions
否则,您应该定义一个静态const
/ constexpr
变量(比如nDef
),其值为2
,并初始化n
和{{1这个常数。
无论如何,请记住,现在Shape()
(Shape
的基类)在 Shape2D
之前初始化,这是该成员类。
答案 1 :(得分:1)
问题是以下两行代码:
int n = 2; //n denotes the number of dimensions
Shape2D(const double side1, const double side2) :Shape(n){ ... }
问题是Shape()
在初始化n
之前执行。有关详细信息,请参阅constructors-called-before-initializing-variables。
要解决此问题,请在Shape
类
protected:
void InitializeBuffer(const int n)
{
sides = new double[n]
}
而不是在父构造函数中初始化sides
,而是在InitializeBuffer
类的构造函数中调用此Shape2D
Shape2D(const double side1, const double side2) :Shape()
{
InitializeBuffer (n);
sides[0] = side1; sides[1] = side2;
}