爲什麼會產生分段錯誤,當我創建一個矩形對象?我在想,我的構造函數有一些不正確的地方,但我沒有足夠的C++經驗來確定它是什麼。分段故障
#include <string>
#include <map>
using namespace std;
class Shape {
private:
string name;
string property_name;
map<string,double> parameters;
public:
Shape(){
}
void set_name(string n){
name=n;
}
string set_property_name(string s){
property_name=s;
}
void set_parameter(string p, double n){
parameters[p]=n;
}
double get_parameter(string p) {
return parameters[p];
}
virtual double get_property() = 0;
};
class Shape2D: public Shape {
public:
Shape2D() {
set_property_name("area");
}
};
class Rectangle: public Shape2D {
public:
Rectangle() {
set_name("rectangle");
set_parameter("length",0);
set_parameter("base",0);
}
double get_property() {
return get_parameter("length") * get_parameter("base");
}
};
int main() {
Shape * user_shape;
user_shape=new Rectangle();
return 0;
}
正常工作在這裏。無法重現。代碼看起來非常好。使用調試器來找出錯誤。 –
'set_property_name(string s)'應該是'void'類型而不是'string'.不能重現問題。 –
@讓FrançoisFabre你需要一個更好的編譯器或更高版本警告:http://coliru.stacked-crooked.com/a/7bee0da403209195 – NathanOliver