Home > Back-end >  Template class how to initialize the array and pointer array?
Template class how to initialize the array and pointer array?

Time:10-17

 
Template
The class Moudle
{
Public:
Moudle (int param);
}

Template
Moudle: : Moudle (int param)
{
STD: : cout}


Simple is fine with the initialization of
 
Moudle A, (15).
Moudle * b=new Moudle (15);

The above two kinds of initialization is ok

But if it is an array or array pointer, how should not implicitly initialized? Such as arrays, pointer array elements 10
 
Moudle C [10];
Moudle (* d) [10];


Initialization in the following way, I want to put in the first 15 parameters, all right, oneself around himself dizzy
 
Moudle C [10] (15)

for(int i=0; i<10; I++)
D [I]=new Moudle (15);

CodePudding user response:

https://blog.csdn.net/qq_25244495/article/details/83661592

CodePudding user response:

 
# include "stdafx. H"
#include
#include
#include
using namespace std;


Template
Class Array2D//said two-dimensional array class
{
Public:
Class Array1D//said one dimensional array class
{
Public:
Array1D ()=default;
T& Operator [] (size_t index)
{
Return const_cast & lt; T&> (static_cast & lt; Const Array1D & amp;> (* this) [index]);
}
Const T& Operator [] (size_t index) const
{
Return arr1 [index];
}
Auto& CreateArr1D (size_t nums)
{
Arr1. Reset (new T/nums);
Return arr1;
}
Array1D (const Array1D & amp;)=the delete;
Array1D & amp; Operator=(const Array1D & amp;)=the delete;
//...
Private:
Unique_ptr & lt; T [] & gt; Arr1 {nullptr};
};
Array2D (size_t dim1, size_t dim2)
{
Arr2. Reset (new Array1D [dim1]);
For (size_t I=0; I & lt; Dim1; I++)
Arr2 [I] CreateArr1D (dim2);
}
Array1D & amp; Operator [] (size_t index)
{
Return const_cast & lt; Array1D & amp;> (static_cast & lt; Const Array2D & amp;> (* this) [index]);
}
Const Array1D & amp; Operator [] (size_t index) const
{
Return arr2 [index];
}
Array2D (const Array2D & amp;)=the delete;
Array2D & amp; Operator=(const Array2D & amp;)=the delete;
//...
Private:
Unique_ptr & lt; Array1D [] & gt; Arr2 {nullptr};
};


//Test:
Int main ()
{
Array2D & lt; Int> P (3, 5);
P [0] [0]=100;
P [2] [4]=200;
Cout & lt;

}

  • Related