Home > Back-end >  VC, not an array of new/delete function how to understand?
VC, not an array of new/delete function how to understand?

Time:10-24

Not to article 3 of the more effective c + + array using polymorphism, in in vs deleteArray function can call success, why?

CodePudding user response:

The so-called polymorphism is for reference and pointer
And array, for each element, is actually the value type of the data, using polymorphism to him, will go wrong,

CodePudding user response:

In an array, the array subscript access element is according to the element size, calculation of the offset array [I] is equivalent to * (array + I * sizeof (T)), when the derived class arrays to a base class pointer to visit again, because of the derived class and a base class size, problems lead to offset,
 class CBase 
{
Public:
CBase () {}
Virtual ~ CBase () {}
};

The class CDrived: public CBase
{
Public:
CDrived () {}
~ CDrived () {}

Private:
Int m_nData;
};

Void FuncArray (const CBase arr [], int nCount)
{
std::cout <& Arr [1] }

Int main ()
{
CDrived arr [3].
std::cout <& Arr [1] FuncArray (arr, 3);

system("pause");

return 0;
}

Results:

You can see the output of two addresses are not the same

CodePudding user response:

 
//vs2017
# include & lt; iostream>
# include & lt; Stdlib. H>
# include & lt; String>
using namespace std;

The class BST
{
Public:
Virtual void print () const
{
Cout & lt; <"BST";
}
};

The class BalanceBst: public BST
{
Public:
Void the print ()
{
Cout & lt; <"BalanceBst";
}

Int a=10;
Int b=20;
};

Ostream & amp; Operator<(ostream & amp; OS, const BST & amp; Item)
{
Item. The print ();
Return cout.
}

Void printBSTArray (ostream & amp; OS, const BST array [], int n)
{
For (int I=0; I & lt; n; + + I)
{
Cout & lt; }
}

Void deleteBSTArray (ostream & amp; OS, BST array [])
{
OS & lt; <"Deleting array";
The delete [] array.
}

//an array base class object, and print the
Void test01 ()
{
BST BSTArray [5].
PrintBSTArray (cout, BSTArray, 5);
}

//an array derived class object and print the
Void test02 ()
{
BalanceBst bBSTArray [5].
PrintBSTArray (cout, bBSTArray, 5);
}

//remove the base class array
Void test03 ()
{
BST * BSTArray=new BST [5];
DeleteBSTArray (cout, BSTArray);
}


//delete the derived class array
Void test04 ()
{
BalanceBst * balBstArray=new BalanceBst [5];
DeleteBSTArray (cout, balBstArray);
}


Test02 () because the array will offset error, why test04 () is not an error?

CodePudding user response:

Because the delete [] with an array of array element address way [I] is not the same as this way, it is not in accordance with the sizeof (T) the way to take, as to how to calculate is about the compiler, the younger brother pretty, don't know, also hope to understand the show just a little down,

CodePudding user response:

You can refer to the https://blog.csdn.net/shandaliuyan/article/details/5930719