正确的模板赋值运算符(成员函数)实现的语法

时间:2012-10-12 02:13:12

标签: c++ templates operator-overloading assignment-operator

这是.hpp文件:

template<typename T>
LinkedQueue<T> operator=(const LinkedQueue<T> & lhs, const LinkedQueue<T> & rhs)
{
  m_data = rhs.m_data;
  m_next = rhs.m_next;
}

错误说第一行必须是非静态成员函数。这是它所在的课程:

template<typename T>
class LinkedQueue:public AbstractQueue<T>
{
public:
  T m_data;
  LinkedQueue *m_next;

  LinkedQueue<T> operator=(const LinkedQueue<T> & rhs);
  LinkedQueue();
  void clear();
  void enqueue(T x);
  void dequeue();
  const T& front() const;
  bool isEmpty() const;

};

知道我做错了什么傻事吗?

2 个答案:

答案 0 :(得分:3)

您应该在函数定义中添加一个类限定符,并删除未使用的lhs参数:

template<typename T>
LinkedQueue<T>& LinkedQueue::operator=(const LinkedQueue<T> & rhs)
//            ^--- & should be added to the declaration, too
{
    m_data = rhs.m_data;
    m_next = rhs.m_next;
    return *this;
}

答案 1 :(得分:1)

你应该写这样的话;

template<typename T>
class LinkedQueue:public AbstractQueue<T>
{
public:
  T m_data;
  LinkedQueue *m_next;

  LinkedQueue<T> & operator=(const LinkedQueue<T> & rhs)
  {
      if (this != &rhs)
      {
          m_data = rhs.m_data;
          m_next = rhs.m_next;
      }

      return *this;
  }
  LinkedQueue();
  void clear();
  void enqueue(T x);
  void dequeue();
  const T& front() const;
  bool isEmpty() const;

};