首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于类模板的有关问题

2012-09-29 
关于类模板的问题定义了一个类模板Collection用来存储Object对象的集合(在一个数组中),以及该集合当前的大

关于类模板的问题
定义了一个类模板Collection用来存储Object对象的集合(在一个数组中),以及该集合当前的大小:
#ifndef Collection_H
#define Collection_H
template <typename Object>
class Collection
{
public:
Collection (Object & initArray)
{
storedArray = initArray;
for(size = 0; *initArray != '\n'; *initArray++)
size++;
}
bool isEmpty() const
{
return size < 1;
}

private:
Object *storedArray;
int size;
};
#endif
然后用一个主程序来测试它:
#include "collection.h"
#include <iostream>
using namespace std;
int main()
{
Collection<char> collection(ch);
if (collection.isEmpty())
cout<<"The collection is empty!"<<endl;

return 0;
}
编译时报错:
error C2664: '__thiscall Collection<char>::Collection<char>(char &)' : cannot convert parameter 1 from 'char [6]' to 'char &'
我使用地址指针来传递数组,但是好像用的有问题。当要使用类模板时,怎样传递数组呢?请求高手解答。

[解决办法]
参考

C/C++ code
#include <iostream>template <typename T, size_t SZ = 32>class Collection{public:    Collection( T (*arg)[SZ])    {        for(size_t i = 0; i < SZ; ++i)        {            data_[i] = (*arg)[i];        }    }        size_t Size() const    {        return SZ;    }    //other methods private:    T data_[SZ];};int main(){    char str[] = "hello world";    Collection<char, sizeof(str)> col(&str);    std::cout << col.Size() << std::endl;    return 0;}
[解决办法]
size_t 是标准库类型,机器相关的,实际上可以看做是unsigned 类型

热点排行
Bad Request.