无法为数组C 添加形状

Unable to add shape to array C++

本文关键字:添加 数组      更新时间:2023-10-16

我正在尝试声明一个新的形状平方

我有点困惑,因为我没有遇到任何错误,但是该程序只是崩溃(但是在删除代码时起作用)

主:

#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 worldn");
    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;
}

square.h:

#include "Shape.h"
using namespace std;
class Square: public Shape
{
    float w,x,y,z;
public:
    void setValues(float,float,float,float);
    Square();
};

shape.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;

这不会导致s特别指向任何内容。在此状态下,使用s的值是不确定的行为。您必须先初始化s才能使用。

通常您会这样初始化它:

Square *s = new Square;

但是,如果这样做,您会发现您的参考错误尚未解决。请阅读此问题,并回答有关此错误的问题。同时,您可以删除这些行:

Square();
Shape();

当您觉得课程需要构造函数时,将其添加回定义。请注意,构造函数是像setValues这样的功能的替代方案。

您需要通过在第9行中调用 Square* s = new Square();来初始化平方对象。在代码中,尚无对象实例,因此您无法调用诸如 s->setValues(1.0f, 2.0f, 3.0f, 4.0f);之类的函数。s这只是一个指向没有有意义的内存位置的指针。