无法为数组C 添加形状
Unable to add shape to array C++
我正在尝试声明一个新的形状平方
我有点困惑,因为我没有遇到任何错误,但是该程序只是崩溃(但是在删除代码时起作用)
主:
#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
这只是一个指向没有有意义的内存位置的指针。
相关文章:
- 如何将元素添加到数组的线程安全函数?
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 添加到数组指针
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 将数组的元素添加到链表中
- 如何在C++中将元素添加到非固定大小的数组中?
- 将在堆栈上声明的元素添加到静态数组
- const_cast静态数组以添加恒常性
- 在 char* 数组中添加两个索引
- c++ 如何在数组的开头添加值并为其编制索引?
- 检查数组中是否有字符串中的值,如果没有,则添加它
- 添加数组特定列的元素
- 添加数组元素:需要左键作为赋值的左操作数
- 添加数组所有元素的 SSE 指令
- 如何添加数组的偶数和奇数之和
- 向std::multimap添加数组值
- 用内部类函数递归地添加数组数
- 使用自增操作符添加数组元素
- 创建一个模板函数,如果数据类型不同,则添加数组的元素