关于类模板中定义一个静态变量[新手]

blueswindxxj 2005-07-29 11:39:11
作用是要完成VB中collection一样的一个池,可以在其中放入对象或各种类型的变量.
我的初步思路是用二个CLASS建立(Collection_class and Collection),一个CLASS(Collection_class)用做存放传放的对象,另一个(Collection)去记录Collection_class的存放地址,用户通过Collection中的方法去找Collection_class中存放的对象,不知道这样的思路对不对!~

在实现时遇到了一个问题:因为是模板,在定义STATIC变量初始化时是老是出错.试了很多次,未果!~望高手帮助给点提示什么的,谢谢!~

此程序还没写完,如果有看不明白的还请多多指导.....

#include <iostream>

using namespace std;

template <class Newtype>
class Collection_class
{
private:
Newtype E; //需要放入的对象
Collection_class *Next; //指向自己的指针
public:
Collection_class()
{
Next=NULL;
}
void Add(Newtype e)
{
E=e;
}
Newtype Get()
{
return E;
}
};

template <class Addtype>
class Collection
{
protected:
Collection_class<Addtype> Head;
Collection_class<Addtype> Temp;
public:
static Collection_class<Addtype> *Last; //定义一个静态的LAST指针记录上一个Collection_class对象的地址,方便放入当前的Collection_class *Next中
void Add(Addtype i)
{
if (Last=NULL)
{
Head.Add(i); //调用Collection_class中的ADD方法存放对象
Last=&Head;
}
else
{
Temp.Add(i);
}
}
Addtype Get()
{
return Head.Get();
}
};

//************** 出 错 处 **********************
template <class Newtype,class Addtype>
Collection_class<Newtype> Collection<Addtype>::Last=NULL; //静态变量初始化,,此为出错的地方,也许不应该这样写......

void main()
{
Collection<double> a;
a.Add(0.12345);
cout<<a.Get()<<endl;
}
...全文
282 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
xzgyb 2005-07-29
  • 打赏
  • 举报
回复
点贴子旁边的管理就可
blueswindxxj 2005-07-29
  • 打赏
  • 举报
回复
分给了吗?!~第一次用,不太会喔!~
blueswindxxj 2005-07-29
  • 打赏
  • 举报
回复
喔!~原来是这样呀!~谢谢!~
xzgyb 2005-07-29
  • 打赏
  • 举报
回复
#include <iostream>

using namespace std;

template <class Newtype>
class Collection_class
{
private:
Newtype E; //需要放入的对象
Collection_class *Next; //指向自己的指针
public:
Collection_class()
{
Next=NULL;
}
void Add(Newtype e)
{
E=e;
}
Newtype Get()
{
return E;
}
};

template <class Addtype>
class Collection
{
protected:
Collection_class<Addtype> Head;
Collection_class<Addtype> Temp;
public:
static Collection_class<Addtype> *Last; //定义一个静态的LAST指针记录上一个Collection_class对象的地址,方便放入当前的Collection_class *Next中
void Add(Addtype i)
{
if (Last == NULL) // 是Last == NULL, 不是Last=NULL
{
Head.Add(i); //调用Collection_class中的ADD方法存放对象
Last=&Head;
}
else
{
Temp.Add(i);
}
}
Addtype Get()
{
return Head.Get();
}
};

//************** 出 错 处 **********************
template <class Addtype>
Collection_class<Addtype> * Collection<Addtype>::Last=NULL; //改为这样
void main()
{
Collection<double> a;
a.Add(0.12345);
cout<<a.Get()<<endl;
}

64,666

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧