简体   繁体   中英

Call constructor inside another constructor (no matching function to call…) c++

I've written an Array class to create 1d,2d and 3d array and it works fine for every test : example of the constructor of the array class for 2d case:

Array::Array( int xSize, int ySize )
{ 
xSize_ = xSize;
ySize_ = ySize;
zSize_ = 1;
vec.resize(xSize*ySize);
}

It works fine , but when i need to use this constructor inside of other constructor, i get the "no matching function error" , part of my code:

class StaggeredGrid
{
public:
StaggeredGrid ( int xSize1, int ySize1, real dx, real dy ) : p_ (2,2) {}
protected:
Array p_;

complete error:

No matching function for call to Array::Array() 
Candidates are : Array::Array(int)
Array::Array(int, int)
Array::Array(int, int, int)

I would appreciate if anybody knows the problem

Your Array class has three constructors, taking one, two, and three ints, respectively. If StaggeringGrid has a default constructor, it will invoke Array::Array(), which doesn't exist, from what you told.

The thing is that then you declare and don't initialize in the StaggeredGrid's constructor

    Array p_;

the default constructor should be called, which seems to be missing in your code.

Simple adding empty default constructor should solve a problem.

    class Array
    {
    public:
        Array(){}
        // ...
    };

Once you define any of the constructor in a class, the compiler does not defines implicitly default constructor for your class.

In your case you've defined parameterized constructor " Array( int xSize, int ySize ) " but your are creating a class with default constructor ie, Array p_ . This invokes your default constructor which is not exactly found by your compiler.

Solution:

Introduce a default constructor in Array class

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