행렬처럼 동작해야하는 클래스가 있습니다. 는 그래서 유스 케이스는 같은 것입니다 :행렬과 같은 클래스의 딥 복사
Matrix matrix(10,10);
matrix[0][0]=4;
//set the values for the rest of the matrix
cout<<matrix[1][2]<<endl;
코드 : 나는 a
그 순간에이 같은 값을 가질 것, 매트릭스의 새로운 인스턴스를 생성 할 const Matrix b = a;
를 호출하여
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <sstream>
using namespace std;
class Matrix {
public:
Matrix(int x, int y);
class Proxy {
public:
Proxy(int* _array) : _array(_array) {
}
int &operator[](int index) const {
return _array[index];
}
private:
int* _array;
};
Proxy operator[](int index) const {
return Proxy(_arrayofarrays[index]);
}
Proxy operator[](int index) {
return Proxy(_arrayofarrays[index]);
}
const Matrix& operator=(const Matrix& othersales);
private:
int** _arrayofarrays;
int x, y;
};
Matrix::Matrix(int x, int y) {
_arrayofarrays = new int*[x];
for (int i = 0; i < x; ++i)
_arrayofarrays[i] = new int[y];
}
const Matrix& Matrix::operator=(const Matrix& othermatrix) {
new (this) Matrix(x, y);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
_arrayofarrays[i][j] = othermatrix._arrayofarrays[i][j];
return *this;
}
int main() {
Matrix a(2, 3);
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
cout << a[1][2] << endl;
//prints out 6
const Matrix b = a;
cout << b[1][2] << endl;
a[1][2] = 3;
cout << a[1][2] << endl;
// prints out 3
cout << b[1][2] << endl;
// prints out 3 as well
}
. 그러나 a
의 값을 변경하면 b
이 영향을받습니다. 따라서 a
에서 일부 값을 변경하면 b
도 변경됩니다. 그리고 나는 그것이 이처럼 행동하는 것을 원하지 않습니다.
a
자체의 영향을받지 않는 b
복사본을 만들어야합니다.
사람들은,하지만 나를 위해, 바보 같은 질문 수 있습니다
[마지막 질문의 답변] (http://stackoverflow.com/a/15753838/16287)을 다시 확인하십시오. 비 const 객체의 경우 operator [] (int index), const 객체의 경우에는 operator [] (int index) const가 필요합니다. 그 중 하나만 가지고 있습니다. –
당신은 상수로 객체를 선언 할 수 없습니다. –
@DrewDormann 맞습니다. 이것을 구현하는 것을 잊었습니다. 내 게시물을 수정하겠습니다. 그럼에도 불구하고 값은 원래 개체의 변경 사항에 의해 영향을 받고 있습니다. – Dworza