【发布时间】:2016-12-11 16:11:04
【问题描述】:
我正在尝试声明一个新形状 Square,稍后将在同一个数组 Shape 中添加一个圆形,该数组是一个抽象类。
我有点困惑,因为我没有收到任何错误,但程序只是崩溃了(但在删除代码后可以正常工作)
主要:
#include "Shape.h"
#include "Square.h"
#include <iostream>
using namespace std;
int main(int argc, char **argv) {
Shape *shapesArray[6];
Square *s;
s->setValues(1.0f, 2.0f, 3.0f, 4.0f);
shapesArray[0] = s;
printf("hello world\n");
return 0;
}
Square.cpp:
#include "Square.h"
void Square::setValues(float w, float x, float y, float z){
this->w = w;
this->x = x;
this->y = y;
this->z = z;
}
方形.h:
#include "Shape.h"
using namespace std;
class Square: public Shape
{
float w,x,y,z;
public:
void setValues(float,float,float,float);
Square();
};
形状.cpp
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
Shape();
protected:
int radius;
float x;
float y;
float w;
float z;
};
【问题讨论】:
-
Square *s是一个简单的指针。它不指向 anything 因为您从未初始化它。所以,调用s->setValues会崩溃。在 C++ 中,分配内存是程序员的工作! -
感谢您提供所有代码,但请在以后将其缩进,not like this。
-
还请注意
using namespace std是不好的做法,在头文件中使用它是非常糟糕的。