[英]Copying an array in c++ - reference
I have a matrix2d class which consists of a dobule A[2][2]. 我有一个由dobule A [2] [2]组成的matrix2d类。 I am trying to do a constructor which takes obejct of the same type and copies all its values to A[2][2]. 我试图做一个构造器,该构造器使用相同类型的对象并将其所有值复制到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. 现在我要创建一个构造函数,该构造函数将使用matrix2D对象,然后将其所有值传递给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. 它告诉我,我尝试将double分配给matrix2d对象。 Why does *Z[i][j] does not reference to a double? * Z [i] [j]为什么不引用双精度数?
SOLVED: I did A[i][j]=ZA[i][j] :)! 解决:我做了A [i] [j] = ZA [i] [j] :)!
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.
}
}
}
There are problem in your copy constructor, you are shadowing one of the members (member name Z
and parameter name Z
). 复制构造函数中有问题,您正在隐藏成员之一(成员名称Z
和参数名称Z
)。
I would suggest to not write your own copy constructor and let compiler generate one for you: 我建议不要编写自己的副本构造函数,而让编译器为您生成一个:
matrix2D(const matrix2D & value) = default;
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. 通常只有在类具有动态分配的成员变量并且需要确保指针值在实例之间没有别名时,才需要使用自定义副本构造函数。
You can certainly do the for-loop technique - and I think that would be good to help in your understanding of arrays and pointers. 您当然可以使用for循环技术-我认为这将有助于您对数组和指针的理解。 But it's hard to beat the efficiency of memcpy
to copy an array of simple types. 但是,很难击败memcpy
来复制简单类型数组的效率。
// Copy Constructor.
matrix2D(const matrix2D& other) {
memcpy(A, other.A, sizeof(A));
memcpy(Z, other.Z, sizeof(Z));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.