【问题标题】:Correct syntax of assignment operator (member function) implementation for a template模板的赋值运算符(成员函数)实现的正确语法
【发布时间】:2012-10-02 19:26:47
【问题描述】:

这是 .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;

};

知道我做错了什么愚蠢的事情吗?

【问题讨论】:

  • 你能改变问题的标题吗?这不是一个好标题。
  • 更具描述性的问题标题可能会吸引更多答案。

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


【解决方案1】:

您应该在函数定义中添加一个类限定符,并删除未使用的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;
}

【讨论】:

    【解决方案2】:

    你应该写成这样;

    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;
    
    };
    

    【讨论】:

      猜你喜欢
      • 2011-05-23
      • 2013-11-13
      • 2015-08-23
      • 1970-01-01
      • 2015-01-27
      • 2021-11-02
      • 2016-05-28
      • 2016-08-27
      相关资源
      最近更新 更多