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

查看:202
本文介绍了c++ - 请教:如何让类模板template的成员函数返回一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

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();
}

这篇关于c++ - 请教:如何让类模板template的成员函数返回一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆