复制构造函数和运算符重载+

时间:2017-03-26 00:40:23

标签: c++

class SmallVector
{
public:

  SmallVector(void);
  SmallVector( const int *tempArr, int arrSize );
  SmallVector( const SmallVector &tempObj );

  int size(void) const;
  int capacity(void) const;

  void push_back(int number); // ++
  void push_back(int *tempArr, int arrSize ); // ++
  int pop_back(void);

  int operator[](int index) const;
  SmallVector operator+(const SmallVector &tempObj);
  SmallVector operator*(int times);
  void printObj(void) const;

  bool isFull(void);

private:

  int staticIndex; // It refers to total element in the static part of the vector

  int dynamicIndex; // it refers to index number of dynamic array(it also refers to number of elements in dynamic section)
  int dynamicSize; // allocated memory for dynamic array

  int staticArray[32];
  int *dynamicArray;

  void expand(int newSize);
  void shrink(void);
};

SmallVector SmallVector::operator+(const SmallVector &tempObj)
{


     int i;

     int totalSize = ( this->size() + tempObj.size() );



     if( totalSize == 0 ) // arguments of sum operator are empty vector
         return SmallVector(); // default constructor is executed




     int *tempArray = new int[totalSize];

     for(i = 0; i < this->size(); ++i)// filling tempArray with first operand
     {
         if(i <= 31)
             tempArray[i] = staticArray[i];
         else
             tempArray[i] = dynamicArray[i - 32];
     }






     for(int j = 0; j < tempObj.size(); ++j, ++i)              
        tempArray[i] = tempObj[j];



     return SmallVector(tempArray, totalSize); // error is here     

}



 SmallVector::SmallVector( const SmallVector &tempObj )

 { // copy constructor



     staticIndex = 0; 

     dynamicIndex = 0;          
     dynamicSize = 0; 




     if( tempObj.size() > 32 ){

         dynamicSize = tempObj.size() - 32;
         dynamicArray = new int[dynamicSize];
     }





     for( int i = 0; i < tempObj.size(); ++i ){


          if( i <= 31 ){  // filling static array

             staticArray[staticIndex] = tempObj[i];
             ++staticIndex;

          }


          else{              

             dynamicArray[dynamicIndex] = tempObj[i];
             ++dynamicIndex;
          }
     }
 }

这实际上是实现了一个矢量项目,但我遇到了非常有趣的问题。如果复制构造函数的参数不是const,则运算符重载+在返回类的临时实例时会给出错误。我认为,编译器对构造函数感到困惑。

错误:没有匹配函数来调用SmallVector :: SmallVector(SmallVector&amp;)

运算符重载+。

中的return语句中会出现此错误

0 个答案:

没有答案
相关问题