Reputation: 1676
I have a matrix2d class which consists of a dobule A[2][2]. I am trying to do a constructor which takes obejct of the same type and copies all its values to A[2][2]. I have a problem, here is the class:
class matrix2D {
public:
double A[2][2];
double Z[2][2];
//Default Constructor.
matrix2D() {
A[0][0] = A[1][1] = 1;
A[0][1] = A[1][0] = 0;
}
matrix2D(double x00,double x01, double x10, double x11) {
A[0][0] = x00;
A[0][1] = x01;
A[1][0] = x10;
A[1][1] = x11;
}
and now I am to create a constructor which takes matrix2D object and then takes all its values to A.
// Copy Constructor.
matrix2D(matrix2D& Z) {
for(int i = 0; i < 2; ++i) {
for(int j = 0; j < 2; ++j) {
A[i][j]=*(Z[i][j]);
}
}
}
It tells my that I try to assign double to matrix2d object. Why does *Z[i][j] does not reference to a double?
SOLVED: I did A[i][j]=Z.A[i][j] :)!
Upvotes: 0
Views: 113
Reputation: 104484
Adding a second answer. And this is the answer I prefer.
Just remove the copy constructor altogether from your class declaration and definition.
Given that your class contains just a pair of fixed sized arrays, you don't need a copy constructor. The compiler will auto generate one for you. A custom copy constructor is typically only needed when your class has dynamically allocated member variables and you need to insure that the pointer values aren't aliased across instances.
Upvotes: 1
Reputation: 1022
There are problem in your copy constructor, you are shadowing one of the members (member name Z
and parameter name Z
).
I would suggest to not write your own copy constructor and let compiler generate one for you:
matrix2D(const matrix2D & value) = default;
Upvotes: 1
Reputation: 206567
The *
in that line does not make sense.
Given the data, you don't need a copy constructor at all. However, if you must implement one, it needs to be something along the lines of:
// Use const&, not just &.
// Use a more suitable variable name for the copy
matrix2D(matrix2D const& copy) {
for(int i = 0; i < 2; ++i) {
for(int j = 0; j < 2; ++j) {
A[i][j]= copy.A[i][j]; // Copy A
Z[i][j]= copy.Z[i][j]; // Copy Z.
}
}
}
Upvotes: 1
Reputation: 104484
You can certainly do the for-loop technique - and I think that would be good to help in your understanding of arrays and pointers. But it's hard to beat the efficiency of memcpy
to copy an array of simple types.
// Copy Constructor.
matrix2D(const matrix2D& other) {
memcpy(A, other.A, sizeof(A));
memcpy(Z, other.Z, sizeof(Z));
}
Upvotes: 0