我在vs代码中编写了C++程序,当我运行它时,它要求我输入元素值,但当我第二次输入时,它已经停止工作。我不知道问题出在哪里,但如果你知道,请帮我解决这个问题。
#include <iostream>
using namespace std;
class myArray {
public:
int total_size;
int used_size;
int* ptr;
myArray(int tsize, int usize)
{
total_size = tsize;
used_size = usize;
ptr = new int(tsize);
}
myArray() {}
void setvalue()
{
int n;
for (int i = 0; i < used_size; i++) {
cout << "Enter the element" << endl;
cin >> n;
ptr[i] = n;
}
}
void show()
{
for (int i = 0; i < used_size; i++) {
cout << "The element in array" << endl;
cout << ptr[i] << endl;
}
}
};
int main()
{
myArray(10, 2);
myArray a;
a.setvalue();
a.show();
return 0;
}
您使用了used_size
和ptr
,但没有在a.setvalue();
和a.show();
中初始化它们。
看来
myArray(10, 2);
myArray a;
应该是
myArray a(10, 2);
此外,正如@Yksisarvien所指出的,
ptr = new int(tsize);
应该是
ptr = new int[tsize];
以分配一个数组而不是单个CCD_ 5。