【发布时间】:2020-05-27 11:54:04
【问题描述】:
为什么无论整数数组对象的定义中指定的值如何,这段代码都会导致数组的第二个元素打印为 0? 下面代码的输出是 7 0 3 4 5 6 而不是 7 2 3 4 5 6,这是什么原因造成的?
// Overloading operators for Array class
#include<iostream>
#include<cstdlib>
using namespace std;
// A class to represent an integer array
class Array
{
private:
int *ptr;
int size;
public:
Array(int *, int);
// Overloading [] operator to access elements in array style
int &operator[] (int);
// Utility function to print contents
void print() const;
};
// Implementation of [] operator. This function must return a
// reference as array element can be put on left side
int &Array::operator[](int index)
{
if (index >= size)
{
cout << "Array index out of bound, exiting";
exit(0);
}
return ptr[index];
}
// constructor for array class
Array::Array(int *p = NULL, int s = 0)
{
size = s;
ptr = NULL;
if (s != 0)
{
ptr = new int[s];
for (int i = 0; i < s; i++)
ptr[i] = p[i];
delete ptr;
}
}
void Array::print() const
{
for(int i = 0; i < size; i++)
cout<<ptr[i]<<" ";
cout<<endl;
}
// Driver program to test above methods
int main()
{
int a[] = {1, 2, 3, 4, 5, 6};
Array arr1(a, 6);
arr1[0] = 7;
arr1.print();
arr1[8] = 6;
return 0;
}
【问题讨论】:
-
user4581301 告诉你原因 - 你的构造函数有未定义的行为。但附带说明一下,不要调用
exit()进行越界访问,而是抛出异常,例如std::out_of_range。您还应该处理index小于0 的情况。此外,由于您正在实现构造函数和析构函数,因此您还应该根据Rule of 3/5/0 实现赋值运算符。在这种情况下,你真的应该改用std::vector。 -
如何抛出 std::out_of_range 异常而不收到“Aborted (core dumped)”消息。
-
catch退出前的异常main()
标签: c++ arrays operator-overloading overloading