【问题标题】:When I overload the assignment operator for my simple class array, I get the wrong answer I expect当我为我的简单类数组重载赋值运算符时,我得到了我期望的错误答案
【发布时间】:2010-05-04 06:59:34
【问题描述】:
//output is "01234 00000" but the output should be or what I want it to be is 
// "01234 01234" because of the assignment overloaded operator
#include <iostream>
using namespace std;
class IntArray
{
public:
  IntArray() : size(10), used(0) { a= new int[10]; }
  IntArray(int s) : size(s), used(0) { a= new int[s]; }
  int& operator[]( int index );
  IntArray& operator  =( const IntArray& rightside );
  ~IntArray() { delete [] a; }
private:
  int *a;
  int size;
  int used;//for array position
};

int main()
{
  IntArray copy;
  if( 2>1)
    {
      IntArray arr(5);
      for( int k=0; k<5; k++)
        arr[k]=k;

      copy = arr;
      for( int j=0; j<5; j++)
        cout<<arr[j];
    }
  cout<<" ";
  for( int j=0; j<5; j++)
    cout<<copy[j];

  return 0;
}

int& IntArray::operator[]( int index )
{
  if( index >= size )
    cout<<"ilegal index in IntArray"<<endl;

  return a[index];
}
IntArray& IntArray::operator =( const IntArray& rightside )
{
  if( size != rightside.size )//also checks if on both side same object
    {
      delete [] a;
      a= new int[rightside.size];
    }
  size=rightside.size;
  used=rightside.used;
  for( int i = 0; i < used; i++ )
    a[i]=rightside.a[i];
  return *this;
}

【问题讨论】:

  • operator[] 中,您可能还应该检查index 是否为负数.. 或设为unsigned
  • 你应该学会使用赋值操作符的复制/交换习语。您提供的代码是标准的第一次尝试,不是异常安全的(甚至不提供基本的异常保证)。

标签: c++ class operator-overloading scope


【解决方案1】:

我认为问题在于您的代码中没有任何地方将 used 设置为 0 以外的任何值,因此当您从 0 循环到 used 时,不会复制任何内容。

您的意思是在分配给operator[] 中的元素时设置used 吗?

此外,如果需要定义析构函数和复制赋值运算符,那么您通常(在这种情况下)也需要提供复制构造函数。

【讨论】:

  • 是的,这是我一个小时以来遇到的问题,谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-11-07
  • 2013-04-05
  • 1970-01-01
  • 2021-10-21
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 2016-12-02
相关资源
最近更新 更多