使用模板编译错误2512 2514 2582 2819

Compile errors 2512 2514 2582 2819 with templates

本文关键字:2512 2514 2582 2819 错误 编译      更新时间:2023-10-16

我从模板开始,我想编码一个链表。

我有很多编译错误:

  • main.cpp(40):错误C2133: 'tmp':未知大小
  • main.cpp(40):错误C2512: 'CNode':没有合适的默认构造函数可用
  • main.cpp(42):错误C2514: 'CNode':类没有构造函数
  • main.cpp(6):参见'CNode'的声明
  • main.cpp(44):错误C2582: 'operator ='函数在'CNode'中不可用
  • main.cpp(45):错误C2819:类型'CNode'不是'operator ->'重载成员
  • main.cpp(6):参见CNode的声明他想用'。"不是吗?
  • main.cpp(45):错误C2232: '-> CNode:: m_next':左操作数类型为'struct';使用"。"
  • main.cpp(45):致命错误C1903:无法从以前的错误中恢复;编译了

#include <iostream>
using namespace std;
template <class T>
struct CNode{
    T data;
    CNode <T> * m_next;
    CNode(T d){
        data = d;
    }
    CNode(T d, CNode *n){
        data = d;
        m_next = n;
    }
};
template <class T>
class CList{
    public:
        bool find(T v);
        bool insert(T v);
        bool remove(T v);
    CNode <T>* m_head;
};
/*
template <class T>
bool CList<T>::find(T v){
    bool isFound = false;
    while( m_head->m_next != NULL){
        if( m_head->m_next.data == value)
            return true;
    }
    return false;
}
    */
template <class T>
bool CList<T>::insert(T v){
    CNode tmp;
    if(m_head == NULL)
        m_head = new CNode(v, NULL);
    else
        tmp = m_head;
        while( tmp->m_next != NULL){
            tmp = tmp->m_next;
            tmp->m_next = new CNode(v, NULL);
        }
    return true;
}
/*
template <class T>
bool CList<T>::remove(T v){
    while( m_head->m_next != NULL){
        if( m_head->m_next.data == value)
            m_head-> m_next = NULL;
            delete m_head;
    }
}
*/
int main(){
    CList <int>test;
    for( int i = 0; i < 10; i++){
        test.insert(i);
//      cout<<test.m_head->data<<endl;
    }
    return 0;
}
 

这是我对你的代码的检查:

一致命名约定
如果要在名前加上'C',则需要在结构体名前加上'S'。

如果你用m_作为数据成员的前缀,你应该将数据字段命名为m_data

不是所有的字段在CNode中初始化
你的构造函数:

  CNode(T d)

不初始化link字段。

使用初始化列表
可以使用初始化列表来简化构造函数:

  CNode(T d)
  : data(t), m_next(NULL)
  { }

两个构造函数可以通过使用默认参数合并为一个构造函数:

  CNode(T d, CNode * p_node = NULL)
  : data(t), m_next(NULL)
  { }

指针不同于对象实例
在你的insert方法中,你给tmp分配一个指针,tmp是一个对象。
应该是:

SNode * p_tmp = NULL;
p_tmp = new SNode(v); // The constructor should set the link field to NULL.
if (m_head == NULL)
{
    m_head == p_tmp;
}
else
{
   SNode * p_node = m_head;
   while (p_node->m_next != NULL)
   {
      p_node = p_node->m_next;
   }
   p_node->m_next = p_tmp;
}

请检查您的代码并查找使用实例而不是指针的实例,反之亦然

我强烈建议您让列表使用静态数据类型,然后转换为模板。这样可以在链表工作的同时消除增加的模板复杂性。