2011-08-01 52 views
2

Period::display()中運行value->getSmall時,該程序編譯的是精細但seg故障。我正在用g ++開發linux。我爲所有可用作T的類提供了getSmall函數。只是爲了確定我添加了調試行,並發現段錯誤是由於類型值(例如T是Class *)而引起的。我遇到了一些常見問題,其中提到了一些問題,如在模板環境中調用獨立值,但我對如何解決這個問題毫無頭緒。模板化成員的調用成員函數

using namespace std; 
template <class T> //T is the class which has to be related & referenced to by period 
class Period 
{ 
    T value;  
public: 

    void display() 
    { 
      cout<<setw(5)<<"| "<< value->getSmall() << "|"; 

       size_t len; //for debug 
       int s;  //for debug 
       char* p=abi::__cxa_demangle(typeid(value).name(), 0, &len, &s); //for debug 
       cout<<setw(5)<<"| "<< p << "|";  //for debug 
    } 

}; 


class Class 
{ 
    string name; 
    timeTable<Teacher*> tt; //class timetable contains pointers to teachers 
    vector<Teacher::teachTimePerClass> teachers; //set of all teachers teaching in a Class with corresponding total time 

    //assigns a teacher to a period in a day 
    bool assign(dayNames day,int periodNum,Teacher *teacher) 
    { 
     tt.assign(day,periodNum,teacher);  //assign the value in this Class's timetable 
     teacher->assign(day,periodNum,this); //update the teacher's timeTable 
    } 

public: 
     static vector<Class*> Classes; //dont forget to destory it at the end!! 


    string getSmall() 
    { 
     return name; 
    } 
}; 
vector<Class*> Class::Classes; 
+0

1.爲什麼你甚至使用指針。 2.段錯誤代碼在哪裏。 –

+0

目前我不明白爲什麼display()應該segfault除了得到小的不返回任何東西。儘管如此,你的編譯器應該會提醒你。 – pmr

+0

@Cat Plus Plus 1)我有許多類的主要列表維護爲一個向量。這段時間應該是「連接」到一個特定的類,因此我雖然我可能會使用指針。你推薦什麼? 2)如果我註釋掉value-> getSmall()部分,則不會發生段錯誤 –

回答

4

您假定T是一個指針,但從未在Period中給它賦值。

這樣你就有一個未初始化的指針可能會出現段錯誤。

+0

牛眼!我忘了完成填充數據的分配功能之一。 –

0
string getSmall() // Class::getSmall() 
{ 
    //return name; 
} 

如果這是你比,你return語句不存在真正的代碼;這是一個未定義的行爲。幸運的是,你正在得到一個分段錯誤。這類錯誤很難追查。在編譯g++時應該提供-Wall選項;它會提示警告等類似的邏輯錯誤。 See demo

+0

對不起,這是否是導致問題的返回值。 –