정수 집합을 나타내는 클래스를 코딩하려고합니다. 숙제가 있지만 나에게있어서이 문제를 이해할 수는 없습니다.C++ : 포인터가 가리키는 값이 변경됩니다.
"IntSet"클래스에는 두 개의 전용 변수가 있습니다. 하나는 배열에 대한 포인터이고 다른 하나는 배열의 크기입니다. 이 클래스의 객체를 만들 수 있으며 의도 한대로 작동합니다. 하지만 IntSet 클래스의 개체를 반환하는 "조인"이라는이 함수가 있습니다. 그것은 기본적으로 배열을 연결 한 다음 해당 배열을 사용하여 반환하는 객체를 만듭니다. 여기
내 코드입니다 :#include <iostream>
using namespace std;
class IntSet {
int * arrPtr;
int arrSize;
public:
//Default Constructor
IntSet() {
int arr[0];
arrPtr = arr;
arrSize = 0;
}
//Overloaded Constructor
IntSet(int arr[], int size) {
arrPtr = arr;
arrSize = size;
}
//Copy Constructor
IntSet(const IntSet &i) {
arrPtr = i.arrPtr;
arrSize = i.arrSize;
}
/*
* Returns a pointer to the first
* element in the array
*/
int* getArr() {
return arrPtr;
}
int getSize() {
return arrSize;
}
IntSet join(IntSet &setAdd) {
//Make a new array
int temp[arrSize + setAdd.getSize()];
//Add the the values from the current instance's array pointer
//to the beginning of the temp array
for (int i = 0; i < arrSize; i++) {
temp[i] = *(arrPtr + i);
}
//Add the values from the passed in object's array pointer
//to the temp array but after the previously added values
for (int i = 0; i < setAdd.getSize(); i++) {
temp[i + arrSize] = *(setAdd.getArr() + i);
}
//Create a new instance that takes the temp array pointer and the
//size of the temp array
IntSet i(temp, arrSize + setAdd.getSize());
//Showing that the instance before it passes works as expected
cout << "In join function:" << endl;
for (int j = 0; j < i.getSize(); j++) {
cout << *(i.getArr() + j) << endl;
}
//Return the object
return i;
}
};
int main() {
//Make two arrays
int arr1[2] = {2 ,4};
int arr2[3] = {5, 2, 7};
//Make two objects normally
IntSet i(arr1, 2);
IntSet j(arr2, 3);
//This object has an "array" that has arr1 and arr2 concatenated, essentially
//I use the copy constructor here but the issue still occurs if I instead use
//Inset k = i.join(j);
IntSet k(i.join(j));
//Shows the error. It is not the same values as it was before it was returned
cout << "In main function:" << endl;
for (int l = 0; l < k.getSize(); l++) {
cout << *(k.getArr() + l) << endl;
}
return 0;
}
이 프로그램은 컴파일하고 지금과 같은 출력은 다음과 같습니다
In join function:
2
4
5
2
7
In main function:
10
0
-2020743083
32737
-2017308032
나는 이유는 모르겠지만, 10, 0마다 항상 동일 다시 컴파일하고 실행할 시간. 또한 포인터의 주소가 아니라 조인 함수와 주 함수에서 값을 인쇄 할 경우, 같은 메모리 주소를 가져옵니다.
죄송합니다. 용어를 오용하면 자바 배경에서 왔으므로 포인터와 같은 것이 나에게 조금 새로운 것입니다. 설명이 필요하면 질문하십시오.
미리 감사드립니다.
생성자에서 로컬 변수를 선언하고 포인터를 유지하면 좋지 않을 수 있습니다. – codah