Home > Back-end >  For bosses, this problem is run locally, right shows how memory transfinite oj in the (is a new prob
For bosses, this problem is run locally, right shows how memory transfinite oj in the (is a new prob

Time:10-07

Question:



Code: # include & lt; Iostream>
using namespace std;
Struct Vect {
Private:
int length=0;
Int * arr;
Public:
Vect (int n) : length (n)
{
Arr=new int (length),
for(int i=0; i{
Arr [I]=0;
}
}
Vect () : length (5)
{
Arr=new int [5].
for(int i=0; i{
Arr [I]=I + 1;
}
}
Vect (Vect& V1) : length (v1. Length), arr (v1. Arr) {};
Void the output ()
{
int i;
for(i=0; i{
cout}
cout}
Void reset (int sit, int number)
{
If (length<=sit)
{
cout<" Out of a boundary "& lt; } else {
Arr (sit)=number;
}
}
Int the Get ()
{
Return length;
}
~ Vect ()
{
The delete [] arr;
}
};
Int main ()
{
int n;
Cin> n;
Vect v2 (n);
Vect v1.
Int sit, number;
Cin> Sit> Number;
V1. The output ();
V2. The output ();
V1. Reset (sit, number);
Vect v3 (v1);
V1. The output ();
V3. The output ();
return 0;
}

CodePudding user response:

Vect (Vect& V1) : length (v1. Length), arr (v1. Arr) {};
Copy constructor is wrong, you this is shallow copy, you need to put the v1 arr copied rather than pointing directly,

CodePudding user response:

reference 1/f, the truth is more important than right or wrong response:
Vect (Vect& V1) : length (v1. Length), arr (v1. Arr) {};
Copy constructor is wrong, you this is shallow copy, you need to put the v1 arr copied rather than pointing directly,

But deep copy function prototype is not X (& amp; X)?? List of parameters, it is my write wrong???????

CodePudding user response:

 
//Vect (Vect& V1) : length (v1. Length), arr (v1. Arr) {};
Vect (const Vect& V1) : length (v1. Length)
{
Arr=new int (length),
for(int i=0; i{
Arr=[I] v1. Arr [I];
}
};

CodePudding user response:

Struct Vect {
Private:
int length=0;
Int * arr;
Public:
Vect ( int) : length (n)
{
If ( length & gt; 0
Arr=new int (length),
The else
Arr=NULL;
for(int i=0; i{
Arr [I]=0;
}
}
Vect (Vect& V1) : length (v1. Length) {
If (length> 0 {
Arr=new int (length),
memcpy (arr, v1. Arr, v1, length * sizeof (int));
} the else
Arr=0;
};
Void the output ()
{
int i;
for(i=0; i{
cout}
cout}
,,,,,,,,
};
  • Related