简体   繁体   English

重载赋值运算符 C++ 传递非常量参数

[英]Overload assignment operator C++ passing non-const parameter

I'm building my own data structures in C++ for university and I've a problem with "queue" data structure.我正在用 C++ 为大学构建自己的数据结构,但“队列”数据结构存在问题。 In particular when I'm trying to overload the assignment operator like this:特别是当我尝试像这样重载赋值运算符时:

Queue& operator=(Queue& C){

   if(this != &C){
     elements = new element_type[C.maxlength];
     maxlength = C.maxlength;
     length = C.length;
     head = C.head;

     if(!C.emptyQueue()){
       for(int i=0; i<length; i++){
         pushQueue(C.readQueue());
       }
       C.pushQueue(C.readQueue());
       C.popQueue();
     }
   }
   return *this;
}

the complier says "cannot bind non-const lvalue reference of type 'Queue&' to an rvalue of type 'Queue'" But, from the moment I need to modify the input parameter (cause to read every value from the queue and push it into the new queue, I need to pop every element) I think it's mandatory to pass it without const.编译器说“不能将'Queue&'类型的非常量左值引用绑定到'Queue'类型的右值”但是,从我需要修改输入参数的那一刻起(导致从队列中读取每个值并将其推入新队列,我需要弹出每个元素)我认为必须在没有 const 的情况下传递它。 Is there another way to do this or I'm missing something?有没有其他方法可以做到这一点,或者我错过了什么?

Your copy assignment operator is actually a move, not a copy assignment.你的复制赋值运算符实际上是一个移动,而不是一个复制赋值。

Use the move assignment:使用移动分配:

Queue& operator=(Queue&& C){

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM