调用模板化成员的成员函数

Calling member function of templated member

本文关键字:成员 函数 调用      更新时间:2023-10-16

此程序编译良好,但在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;

您假设T是一个指针,但在Period中从不给它一个值。

这样你就有了一个未初始化的指针,很可能出现段错误。

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

如果这是你的真实代码,你的return语句缺失;这是一个未定义的行为。幸运的是,你得到一个分割错误。这种bug很难追踪。在使用g++编译时,应该提供-Wall选项;它会提示诸如警告之类的逻辑错误。看到演示。