C++段异常有关问题
C++段错误问题
为什么这样就会出现段错误阿?
如果把后面几句换成这样:
就没问题,求解为什么?
------解决方案--------------------
数组访问越界了。。!设数组元素个数为n个!则下标为0到n-1
你把s[1]、s[2]改成s[0]和s[1]即搞定
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
class Shape {
public:
virtual void ShowArea(void)const = 0;
};
class Circle: public Shape {
private:
double radius;
static double PI;
public:
Circle(double r = 0):radius(r) {}
void ShowArea(void) const {
cout << radius * radius * PI << endl;
}
};
class Square: public Shape {
private:
double width;
double length;
public:
Square(double w = 0, double l= 0 ):width(w), length(l) {}
void ShowArea(void) const {
cout << width * length << endl;
}
};
double Circle::PI = 3.1415926;
int main(void)
{
Shape *s[2];
Circle c(3);
Square sq(2, 3);
s[1] = &c;
cout << s[1] <<endl;
s[2] = &sq;
cout << s[2] <<endl;
s[1]->ShowArea();
s[2]->ShowArea();
}
为什么这样就会出现段错误阿?
如果把后面几句换成这样:
s[1] = &c;
cout << s[1] <<endl;
s[1]->ShowArea();
s[2] = &sq;
cout << s[2] <<endl;
s[2]->ShowArea();
就没问题,求解为什么?
------解决方案--------------------
数组访问越界了。。!设数组元素个数为n个!则下标为0到n-1
你把s[1]、s[2]改成s[0]和s[1]即搞定