【问题标题】:invalid initialization of reference type?引用类型的初始化无效?
【发布时间】:2014-09-24 23:35:32
【问题描述】:

发生了什么事?这是它引用的函数。我试图让它作为复制构造函数工作

template <class T>
const queue<Base>& queue<T>::operator=(const queue<Base> &q){
// Doesn't need to copy if they are the same object
if (this != &q){
    delete [] data;

    length = q.length;
    capacity = q.capacity;
    front = q.front;

    data = new T[capacity];

    for (int i = 0; i < capacity; i++){
        data[i] = q.data[i];
    }
}

return this;
}

【问题讨论】:

  • 当您询问有关错误消息的问题时,通常会指定产生错误的行。我们应该如何知道哪一行是第 23 行(或 190 行)?
  • 为什么需要赋值运算符?使用向量而不是原始数组,默认的会自动工作。
  • 请注意,operator= 应该返回一个 非 const 引用。
  • 这是赋值运算符,不是复制构造函数。
  • 您可能希望复制到 length 而不是 capacity

标签: c++ compiler-errors


【解决方案1】:

这是你的错误

return this;

this 是一个指针。您的 operator = 被声明为返回引用。指针不能转换为引用。这就是错误消息告诉您的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 2012-12-18
    • 2020-06-12
    • 2015-01-26
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 2013-01-07
    相关资源
    最近更新 更多