简体   繁体   中英

How to initialize a list of struct with constructor in c++

I have a struct with a constructor likes:

struct Rectangle
{
    int width;
    int height;

    Rectangle(int _width, int _height)
    {
        width = _width;
        height = _height;
    }
}

And I create a Rectangle that is okay: Rectangle rect = Rectangle(4, 8);

But how to create a list a Rectangle struct with constructor: Rectangle rects[10];

That is an error: no default constructor exists for class "Rectangle".

Does it not allow create a list if I define a constructor in struct?

And how do I fix it?

Thanks!

The "no default constructor" means there's no constructor that takes no arguments . You have one that takes 2. The compiler can't just make up values, it needs to know exactly what values to supply.

You can easily make this a default constructor by adjusting the signature to include defaults:

Rectangle(int _width = 0, int _height = 0)

Now it's usable as a default.

I think the spirit of the question might be rooted in you thinking about arrays in a more Java or C#-like way.

When you say Rectangle[10] in C++, it's directly allocating 10 contiguous rectangle objects, in this case on the stack in memory. If you did not have a constructor, it would use the 'default' constructor, setting the x and y members to their 'default' values (which are not 0, by the way).

Since you have designated a constructor, the compiler is inferring that you want to require that the class be instantiated with those two values!

If you want to provide a default constructor for situations such as this, try this:

Rectangle(): x(0), y(0) {}

And I create a Rectangle that is okay: Rectangle rect = Rectangle(4, 8);

Sure: But I would do it like:

 Rectangle rect{4, 8};

This form will come in useful in a second.


But how to create a list a Rectangle struct with constructor: Rectangle rects[10];

Rectangle rects[10] = {{1,2}, {2,3}, {3,4}, {4,5}, {6,7}, {1,2}, {2,3}, {3,4}, {4,5}, {6,7}};

That is an error: no default constructor exists for class "Rectangle".

That is because this:

 Rectangle rects[10];  // creates 10 Rectangles.
                       // There is no constructor with zero arguments
                       // so it can not create them

Several options here:

 // This allows multiple ways to construct a rect.
 Rectangle(int _width = 0, int _height = 0)
     : width(_width)
     , height(_height)
 {}

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