C++ Array 类的运算符重载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13093520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:57:00  来源:igfitidea点击:

operator overloading for Array class

c++overloading

提问by user1776433

i am trying to overload operators << >> != == = and [] for Array class. The app crashes on run, though no compilation errors are shown. what could possibly be wrong? IDE used dev c++

我正在尝试为 Array 类重载运算符 << >> != == = 和 []。应用程序在运行时崩溃,但没有显示编译错误。可能有什么问题?IDE 使用 dev c++

Here's array.h

这是 array.h

#ifndef ARRAY_H
#define ARRAY_H

#include <iostream>
using namespace std;

class Array{
  friend ostream & operator << ( ostream &, const Array & );
  friend istream & operator >> ( istream &, Array &);
  private:
         int size;
         int * ptr;
  public:
         Array ( int = 10 );
         Array ( const Array & ); //copy constructor
         ~Array ();
         const Array &operator=( const Array & ); 
         bool operator == ( const Array & ) const; 
         bool operator != ( const Array & ) const;
         const int operator [] (int) const; 
         int getSize() const;            
};

#endif

and now array.cpp

现在 array.cpp

#include <iostream>
using namespace std;
#include "array.h"

Array::Array (int sze ){ //default constructor edited
         size = (sze > 0 ? sze : 10);
         ptr = new int [ size ];
         for (int i = 0;  i < size; i++)
             ptr[ i ] = 0; //initial values
}
Array::Array (const Array & arr ): size(arr.size){
         ptr = new int [size];
         for ( int i = 0; i< size; i++)
             ptr [ i ] = arr.ptr [ i ];
}
Array::~Array(){
         delete [] ptr;
}
const Array &Array :: operator= ( const Array & right){//IMPO
         if(&right != this){ //edited self assignment test
                   if(size != right.size){//diff sized arrays
                           delete [] ptr; //reclaim space
                           size = right.size; 
                           ptr = new int [ size ]; //space created
                   }
         }
         for(int i=0; i<size; i++)
                 ptr[ i ] = right.ptr[ i ];
         return *this;     //enables cascading a=b=c       
}
bool Array::operator == ( const Array & right) const{
         if ( size != right.size )
            return false;
         for ( int i =0; i < size; i++ ){
             if ( ptr [ i ] != right.ptr[ i ] )
                return false;
         }
         return true;
 }
bool Array::operator != ( const Array & right ) const{ //edited
         return ! (*this == right);
}
const int Array::operator [] (int subscript) const{
         if(subscript >=0 && subscript < size)
            return ptr[ subscript ];      
}
int Array::getSize() const{ return size; }  
//friend functions not in .h
ostream & operator << ( ostream & output, const Array & array){
         for (int i = 0; i < array.size; i++)
             output << array.ptr[i] ; 
}
istream & operator >> ( istream & input, Array & array){
         for (int i = 0; i < array.size; i++)
             input >> array.ptr[i];
}

now main.cpp

现在 main.cpp

#include <cstdlib>
#include <iostream>
#include "array.h" // " " not <>
using namespace std;

int main(int argc, char *argv[])
{
Array a1(7),a2 (-1),a4; //changed a2
cout<<"Input "<<a1.getSize()<<" integers for Array object a1 and "<<a2.getSize()<<" integers for Array objecta2\n";
cin>>a1>>a2;
cout<<"a1 and a2 are\n";
cout<<a1<<endl<<a2;
cout<<"a1!=a2 : "<<(a1!=a2)<<endl;
cout<<"a1 ==a2: "<<(a1==a2)<<endl;
cout<<"Printing a1[5] : "<<a1[5]<<endl;
Array a3(a1); 
a4 = a3;

system("PAUSE");
return EXIT_SUCCESS;
}

回答by Alex

You have to reserve memory for ptrin the constructor.

您必须ptr在构造函数中保留内存。

Array::Array (int size ){ //default constructor
         size = (size > 0 ? size : 10);
         ptr = new int [size]; // ADD THIS LINE
         for (int i = 0;  i < size; i++)
             ptr[ i ] = 0; //initial values
}

There are some other problems with your code that are not the direct source of the crash but are worth noting:

您的代码还有一些其他问题,这些问题不是崩溃的直接来源,但值得注意:

  1. Array::operator !=is defined in terms of itself. It should be similar to operator==, or you can re-use it with

    if( *this == right )
        return false;
    return true;
    
  2. Array::operator []should probably throw an exception if the index is out of bounds. Currently it just returns garbage memory.

  3. Inside Array::Array (int size )the assignment to sizeassigns to the parameter, not to the member. Change the first line to:

     this->size = (size > 0 ? size : 10);
    
  4. operator<<and operator>>should return outputand input, respectively.

    ostream & operator << ( ostream & output, const Array & array){
       for (int i = 0; i < array.size; i++)
           output << array.ptr[i] ; 
       return output;
    }
    
  1. Array::operator !=是根据自身定义的。它应该类似于operator==,或者您可以重新使用它

    if( *this == right )
        return false;
    return true;
    
  2. Array::operator []如果索引超出范围,可能应该抛出异常。目前它只返回垃圾内存。

  3. Array::Array (int size )赋值内部分配size给参数,而不是分配给成员。将第一行更改为:

     this->size = (size > 0 ? size : 10);
    
  4. operator<<operator>>应该分别返回outputinput

    ostream & operator << ( ostream & output, const Array & array){
       for (int i = 0; i < array.size; i++)
           output << array.ptr[i] ; 
       return output;
    }
    

回答by Andrii

Also, you have en error in your implementation of operator !=at line: if ( *this != right )- recursive definition, so, stack overflow.

此外,您在执行operator !=at 行时出错: if ( *this != right )- 递归定义,因此,堆栈溢出。

回答by BigBoss

You have 2 errors in your default constructor:

您的默认构造函数中有 2 个错误:

1) You do not allocate memory for ptrand you try to initialize it, this is certainly an error and cause an undefined behavior, so if you have some invalid value in ptryou may get a segmentation fault or worse you may overwrite value of some of your internal variables!

1)您没有为其分配内存ptr并尝试对其进行初始化,这肯定是一个错误并导致未定义的行为,因此如果您有一些无效的值,ptr您可能会遇到分段错误或更糟的是您可能会覆盖您的某些值内部变量!

2) Name of variable of the default constructor is size and size = (size > 0 ? size : 10);change value of local variable sizenot the sizemember of your class, and because of that your sizemember will remain uninitialized and any use of that is illegal and you may still get exceptions like segmentation fault(for example sizemay be 7476327436that certainly is far beyond end of your array.

2)默认构造函数的变量名称是size = (size > 0 ? size : 10);局部变量的大小和更改值而size不是size您的类的成员,因此您的size成员将保持未初始化状态,任何使用都是非法的,您仍然可能会遇到诸如分段错误之类的异常(例如size可以7476327436肯定是远远超出你的阵列的结束。

and beside that you have 1 error in your operator !=, since you have if ( *this != right )and that will use operator !=for comparison, and this is a recursive function in all cases and you will get a stack overflow exception, so if you want to check for exact pointers use if ( this != right )instead of that.

除此之外,您的 中有 1 个错误operator !=,因为您有if ( *this != right )并且 将operator !=用于比较,并且在所有情况下这是一个递归函数,您将收到堆栈溢出异常,因此如果您想检查确切的指针,请使用if ( this != right )而不是那。

I don't fully check your code first time that I see it, but you have some other errors in your code and I don't know how you even compile it, In multiple places you do not provide return value for your function. Please remember Never ignore compiler warningsthere exist to help you correct your programming errors:

我第一次看到你的代码时没有完全检查它,但是你的代码中有一些其他错误,我不知道你是如何编译它的,在多个地方你没有为你的函数提供返回值。请记住永远不要忽略编译器警告存在以帮助您纠正编程错误:

const int Array::operator [] (int subscript) const{
    if(subscript >=0 && subscript < size)
        return ptr[ subscript ];
    // If not what should I do?? add a return value here, this is a warning
    // since compiler think somehow you know that your code never reach here
    // but do you really know??
    return 0;
}
ostream & operator << ( ostream & output, const Array & array){
    for (int i = 0; i < array.size; i++)
        output << array.ptr[i] ;
    // You say that your function return an ostream& but where is it??
    // this is an error so compiler have nothing to return instead of you!
    // And if your compiler does not generate an error possibly it return 
    // junk value that will cause an error!!
    return output;
}
istream & operator >> ( istream & input, Array & array){
    for (int i = 0; i < array.size; i++)
        input >> array.ptr[i];
    // again you forget to return an istream& and again this is an error
    return input;
}

but beside that I see no error in your code and it should run with no error

但除此之外,我在你的代码中没有看到任何错误,它应该没有错误地运行