2016-09-29 123 views
0

爲什麼會產生分段錯誤,當我創建一個矩形對象?我在想,我的構造函數有一些不正確的地方,但我沒有足夠的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; 
} 
+2

正常工作在這裏。無法重現。代碼看起來非常好。使用調試器來找出錯誤。 –

+0

'set_property_name(string s)'應該是'void'類型而不是'string'.不能重現問題。 –

+1

@讓FrançoisFabre你需要一個更好的編譯器或更高版本警告:http://coliru.stacked-crooked.com/a/7bee0da403209195 – NathanOliver

回答

4

因爲你string set_property_name(string s)沒有return,是不確定的行爲

+1

我不能編譯'set_propert_name(string s)''void'.How不會返回創建segFault。 –

+0

@GauravSehgal也許你會添加一些標誌,你的編譯器會把*看作是錯誤? –

+1

@GauravSehgal有些編譯器會讓編譯器沒有返回語句,因爲它們只發出警告而不是錯誤。在這種情況下,當代碼達到它嘗試訪問返回值的地步,但沒有提供返回值時,就會出現段錯誤。 – NathanOliver