C ++: Simple two-dimensional array with Proxy Class.

xiaoxiao2021-03-06  81

In these days, I saw more Effective C . See Terms 30: Proxy Class referred to the use of Proxy Class to implement two-dimensional array, but there is no complete instance on the book, I spent some time I wrote a simple . Just achieve the most basic functions, some exception handling does not join.

#include using namespace std;

Template class array2d {public: int D1, D2; Array2D (int Dim1, Int Dim2); ~ Array2D ();

Class Array1D {public: array1d (int Dim) {m_d = new t [DIM];

~ Array1d () {delete [] m_d;}

T * m_d;

T & Operator [] (int index) {return m_d [index];}}; array1d ** m_1d; array1d & operator [] (int index);

Template array2d :: array2d (int Dim1, int Dim2) {m_1d = new array1d * [dim1]; for (int i = 0; i

D1 = DIM1; D2 = DIM2;

Template array2d :: ~ array2d () {for (int i = 0; i

delete [] m_1d;

// Template // array2d :: array1d :: array1d (int Dim) // {// m_d = new T [DIM]; //}

Template array2d :: array1d & array2d :: operator [] ("{return * m_1d [index];} // Template // t & array2d :: Array1D :: Operator [])) {// Return M_D [INDEX]; //}

Int main () {Array2D Data (3, 5);

For (int i = 0; i <= 2; i ) {for (int J = 0; j <= 4; j ) {data [i] [j] = i j;}}

For (int i = 0; i <= 2; i ) {for (int J = 0; j <= 4; j ) {cout << Data [i] [j] << ";} cout << Endl }} Run results: 0 1 2 3 41 2 3 4 52 3 4 5 6

Everyone may see that there are some comments from the code. Since I am not very familiar with the template, the constructor of Array1D and the overload function of [] are not written in the class during the beginning. Like a comment, write outside the class, but compile time report: E: / Visual C Projects / Pointer / A.CPP (85): Error C3206: "Array2D :: array1d :: array1d": Can't Member function of nested classes of the external definition template class

So I defined these functions to the interior of the class. This also studied a little extra stuff. At the same time, I would like to thank Kingfox (Little Fox), he pointed out a mistake in my code: Template Array2D :: Array1D & Array2D :: Operator []DEX) {Return * m_1d [index }

At the beginning, I forgot to define the return value as reference, resulting in an error.

转载请注明原文地址:https://www.9cbs.com/read-121735.html

New Post(0)