读书人

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

发布时间: 2012-09-28 00:03:35 作者: rapoo

模板问题“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只是复制一个临时变量出来,但是不能直接对元素操作了
[解决办法]
编译不过? 你仔细检查一下代码 声明和实现

读书人网 >C++

热点推荐