C++ 在模板类中重载运算符时遇到问题

C++ Trouble overloading operators in a template class

本文关键字:运算符 遇到 问题 重载 C++      更新时间:2023-10-16

每次我在运算符的定义中添加注释时,它都会开始给我错误,但删除注释会立即消除错误。我不明白为什么注释会对代码产生任何影响。此外,关于运营商超载的一般建议也将不胜感激。

这是我的类模板:

template<class THING>
struct LLNode
{
  THING data;
  LLNode<THING> *next;
  LLNode<THING> *prev;
};
template<class THING>
class LinkedList
{
private:
     //use a doubly linked-list based implementation
     //keep a head and tail pointer for efficiency
     LLNode<THING> *Head;
     LLNode<THING> *Tail;
     int count;
public:
     //setup initial conditions
     LinkedList();
     //delete all dynamic memory, etc.
     ~LinkedList();
     //constant bracket operator to access specific element
     const THING& operator[](int);
     //Bracket operator to access specific element
     THING& operator[](int);
     //Equality operator to check if two lists are equal
     bool operator==(const LinkedList<THING>&);
     //Inequality operator to check if two lists are equal
     bool operator!=(const LinkedList<THING>&);
     //add x to front of list
     void addFront(THING);
     //add x to back of list
     void addBack(THING);
     //add x as the ith thing in the list
     //if there are less than i things, add it to the back
     void add(THING, int);
     //remove and return front item from list
     THING removeFront();
     //remove and return back item from list
     THING removeBack();
     //return value of back item (but don't remove it)
     THING getBack();
     //return value of front item (but don't remove it)
     THING getFront();
     //return how many items are in the list
     int length();
     //print all elements in the linked list
     void print();
};

我目前正在研究的运营商:

template<class THING>
THING& LinkedList<THING>::operator[](int index)
{
}
template<class THING>
bool LinkedList<THING>::operator==(const LinkedList<THING>& list_one, const LinkedList<THING>& list_two)
{
    //checking for same size on both lists
    //if both are same size, move on to checking for same data
    if(list_one.count != list_two.count)
    {
        return false;
    }
    else
    {
        //boolean flag to hold truth of sameness
        bool flag = true;
        //two pointers to go through
        LLNode<THING> *temp_one = list_one.Head;
        LLNode<THING> *temp_two = list_two.Head;
        while(temp_one != NULL && temp_two != NULL)
        {
            if(temp_one->data != temp_two->data)
            {
                flag = false;
                break;
            }
            else
            {
                temp_one = temp_one->next;
                temp_two = temp_two->next;
            }
        }
        return flag;
    }
}

正如你所说,这些不是编译错误:它们是智能感知错误。这些错误需要一段时间才能在扩展中刷新,因此大多数时候不是很指示,这是一个已知问题,智能感知在添加注释方面并不擅长,并且在与其他扩展发生冲突时更糟。

消除错误的一种方法是剪切粘贴所有代码(只需ctrl + a,ctrl + x,ctrl + v)。这会强制智能感知刷新。

我个人最喜欢的另一种方法是关闭智能感知:)您可以在此处了解如何执行此操作。