Initialization

zhaozj2021-02-11  195

Initialization class object Zhao Xiangning question: How to initialize table data in C ? In C language, I can initialize the structure array like this: //

Struct mystruct {

INT X, Y, Z;

}

MyStruct Table [] = {

{1, 2, 3},

{4, 5, 6},

... // ETC

}

/ / But if MyStruct is a C class, not a structure, I have error. I think this is a shortcoming of C . Answer: This problem is completely dependent on how you look at C . One of the advantages of C is to force you to do the right thing. For example, C does not like to create an object when the constructor is called. This is why you can't use the original data to initialize the class object, whether it is part array or other data. The purpose of the constructor is to ensure that each object is correctly initialized, whether you are from the program stack, the memory can be allocated, or as a static array element. Let the original data bypass the constructor is taboo. Also causing you to create object static arrays with initial data - you must call constructor! //

Class cfooble {

INT X, Y, Z;

PUBLIC:

Cfooble (int xx, int yy, int zz)

: x (xx), y (yy), z (zz) {...}

Cfooble (INT I) {x = y = z = i;}

}

Cfooble Table [] = {

Cfooble (1, 2, 3),

CfoOBLE (4, 5, 6),

Cfooble (0), // can use any constructor!

}

// The following code is a complete example that can be compiled. //

// StaticClassArray - Explains how to initialize static C array in C objects

// The compilation method is as follows:

//

// Cl Fooble.cpp

//

#include

//

// A typical class - there are three data members ...

//

Class cfooble {

protected:

INT X, Y, Z;

PUBLIC:

// Two constructor ...

Cfooble (INT I) {x = y = z = i;}

Cfooble (int xx, int yy, int zz): x (xx), y (yy), z (zz) {}

// an output function

Void print () {

Printf ("cfooble at% P: (% D,% D,% D) / N", THIS, X, Y, Z);

}

// This function checks if it is empty ...

INT ISEMPTY () {

Return x == 0 && y == 0 && z == 0;

}

}

#ifdef never

// This will not be running - can't "post hard" to initialize the C class object!

Cfooble Table [] = {

{1, 2, 3},

{4, 5, 6},

{0,0,0}

}

#ENDIF

/ / The following is how to initialize a category:

Cfooble Table [] = {

Cfooble (1, 2, 3),

CfoOBLE (4, 5, 6),

Cfooble (0), // can even use different constructors!

}

void main ()

{

For (cfooble * pc = table;! pc-> iSempty (); pc ) {

PC-> Print ();

}

}

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

New Post(0)