簡體   English   中英

模板成員的調用成員函數

[英]Calling member function of templated member

當在Period::display()運行value->getSmall時,該程序編譯良好,但存在段錯誤。 我正在使用g ++在Linux上工作。 我為所有可用作T的類提供了一個getSmall函數。 只是為了確保我添加了調試行,並發現segfault是在值的類型(即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;

您假設T是一個指針,但是永遠不要在Period給它一個值。

這樣,您就有了可能會出現段錯誤的未初始化指針。

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

如果這是您的真實代碼,則缺少return語句; 這是未定義的行為。 幸運的是,您遇到了細分錯誤。 這種錯誤很難追蹤。 使用g++編譯時,應提供-Wall選項; 它將提示諸如警告之類的邏輯錯誤。 參見演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM