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

模板有关问题“T& 而不是T”

2012-09-28 
模板问题“T& 而不是T”C/C++ codetemplateclass Tclass MyArray{public:MyArray(){m_ptData NULLm_nCo

模板问题“T& 而不是T”

C/C++ code
template<class T>class MyArray{public:    MyArray()    {         m_ptData = NULL;         m_nCount = 0;        m_ptData = new T [1];    }    int Add(const T *pTItem){...}    inline T& operator[](int nIndex) const;    T          *m_ptData;    int    m_nCount;};//这里返回值为什么是T& 而不是T, m_ptData[nIndex]就是真实的地址即pctsttemplate<class T>inline T& MyArray<T>::operator[](int nIndex) const {    return m_ptData[nIndex];}




C/C++ code
//保存    CTest *pctst = new CTest;    (const_cast<CTest*>(pctst))->i = 10;    g_Array.Add(&pctst);





C/C++ code
//使用    int nIndex = 0;    for(nIndex = 0; nIndex < 1; nIndex++)    {        CTest *p = g_Array[nIndex];        if (p != NULL)        {            int xx =p->i;        }    }


[解决办法]
这样可以通过下标赋值
[解决办法]
返回T只是复制一个临时变量出来,但是不能直接对元素操作了
[解决办法]
编译不过? 你仔细检查一下代码 声明和实现

热点排行