【问题标题】:Unable to add shape to array C++ [duplicate]无法将形状添加到数组 C++ [重复]
【发布时间】: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-&gt;setValues 会崩溃。在 C++ 中,分配内存是程序员的工作!
  • 感谢您提供所有代码,但请在以后将其缩进,not like this
  • 还请注意using namespace std 是不好的做法,在头文件中使用它是非常糟糕的。

标签: c++ arrays


【解决方案1】:
Square *s;

这不会导致s 指向任何特定的东西。在这种状态下使用s 的值是未定义的行为。您必须先初始化s,然后才能使用它。

通常你会这样初始化它:

Square *s = new Square;

但是如果你这样做,你会发现你有一个未解决的参考错误。请阅读this question and answer 了解此错误。同时,您可以删除这些行:

Square();
Shape();

当您觉得您的类需要构造函数时,将它们添加回来,并带有定义。请注意,构造函数比setValues 之类的函数要好得多。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-04-04
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 2020-06-05
      • 2021-05-31
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多