首页 > 开发 > C++ > 正文

请教:如何让类模板template的成员函数返回一个类?

2017-09-11 21:19:20  来源: 网友分享

我先请教一个简单的类的成员函数返回一个类的片段:

class T { private:      vector<int> times; public:      T* sample(int n)      {          T* S = new T;          for (int i=0; i<n; i++)  S->times.push_back(i*2);          return S;      }      void display(int n)      {          for (int i=0; i<n; i++)  cout << " " << times[i];      } }; 

这段程序非常简单,无非是在类T里新建一个类S然后让成员函数sample返回S。但是在main()里运行却发现,无法调用S的成员函数display?!

int main()      {T t;      T* s = t.sample(10);      s.display(9);} // **此处报错为“Segmentation fault”,请问是s的display()有什么问题吗?**

然后假设上一个问题已经解决,同样是在类T里新建一个类S然后让成员函数sample返回S,但是这次需要在模板template里做。

template <typename T> class TTT { private:      vector<T> times; public:      TTT<T> * sample(uint64_t a, uint64_t b=0);      {          ...          TTT *S = new TTT; // **这样写有问题。那么应该怎么写呢?**          return S;      }      display(); }; 

那么在TTT<T>里面应该怎样新建S、并且返回S呢?后续的S.display()是不是依旧有问题呢?

谢谢啦先!

解决方案

  1. 你的s是个指针啊, 当然应该用operator->啦, 你现在用了operator.了.

    template <typename T> class TTT    {    private:        vector<T> times;    public:        TTT<T> * sample(uint64_t a, uint64_t b = 0)        {            TTT<T> *S = new TTT;            S->times.push_back(a);            S->times.push_back(b);            return S;        }        void display()        {            std::cout << times[0] << " " << times[1] << std::endl;        }    };    int main()    {        T t;        T* s = t.sample(10);        //s->display(9);        TTT<uint64_t> *ttt = nullptr;        ttt = ttt->sample(1, 2);        ttt->display();    }

或者用静态成员函数

template <typename T> class TTT{private:    vector<T> times;public:    static TTT<T> * sample(uint64_t a, uint64_t b = 0)    {        TTT<T> *S = new TTT;        S->times.push_back(a);        S->times.push_back(b);        return S;    }    void display()    {        std::cout << times[0] << " " << times[1] << std::endl;    }};int main(){    T t;    T* s = t.sample(10);    //s->display(9);    TTT<uint64_t> *ttt = TTT<uint64_t>::sample(1, 2);    ttt->display();}