![]() |
#2
rjsp2017-08-09 08:29
|

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];
}
};
{
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 t;
T* s = t.sample(10);
s.display(9);}
然后假设上一个问题已经解决,同样是在类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();
};
{
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()是不是依旧有问题呢?
谢谢啦先!