简体   繁体   中英

C++ Array initialization

the code below gives compilation error when I try to create test t[2]; because there is no default constructor for this.

But if I create Test t[2] = {test(1,2), test(2,3)}; Then it works fine.

1)But think of a situation, if we want to create more then 100 array element. We need to create 100 element in the curly braces like.. Test t[100] = {test(1,2), test(1,2)……/ 100 times /};

The above code is difficult to maintain. One more solution is to create public member function which takes 2 integers and run in a loop. This solves the problem but i want to know any other good method.

2) If I create it using new

Test *t = new test[10];

I get compilation error(No default constructor). How to solve this.

class test
{
    int _a;int _b;

public:
    test(int a, int b);
    void display();
};


int _tmain(int argc, _TCHAR* argv[])
{
    test t[10];

    for (int i = 0 ; i< 10; i++)
        t[i].display();
}

In order to construct your 10 elements in the array the compiler somehow has to instaciate them through a constructor. For arrays only a default constructor (taking no arguments) can bes used, as you can not pass any arguments to the elements in the array. Therfor you have to proved a constructor

test::test()

taking no arguments.

In your example what do you expect to be displayed?
If you know that, you can write a Default CTor (one that has no parameters) and set your values to the defaults.

An example of the Default CTor:

// Variant 1: Use the initialization list
test()
: a(-1)
, b(-1)
{
}

// OR
// Variant 2: Do it in the CTor's body
test()
{
    a = -1;
    b = -1;
}

Note: You can write several CTors (it's called "overloading"). One that takes no parameters and sets default values and others that take parameters and set those values.

You can also define a constructor with default values for all parameters which will be used as the default constructor.

test(int a = 0, int b = 0) :_a(a), _b(b) {}

Since all parameters have default values, this constructor will be used as the default. Leaving out the initialization list or not initializing the member variables in the body of the constructor may give you random data values. Some systems may zero all memory allocations, but some do not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM