简体   繁体   中英

No matching function call C++

I'm getting the above error in C++ when trying to initialise an object of type Board. The constructor for board takes in two integers, so it's

Board::Board(int w, int h)

And I'm trying to create a Connect Four game. The ConnectFour.h file has the following:

Board b;

in its private variables, and the constructor in ConnectFour.cpp is this:

ConnectFour::ConnectFour()
{
   Board b(7, 6);

among other things, obviously.

It's giving me the error:

In constructor 'ConnectFour::ConnectFour(int, int)':|

error: no matching function for call to 'Board::Board()'|

note: candidates are:|

note: Board::Board(int, int)|

note: candidate expects 2 arguments, 0 provided|

If anyone could lend a hand, I'd really appreciate it.

Edit: Turns out I was being a bit silly. Thanks guys.

You need to supply a constructor for board that takes no parameters to work with your Board b; code, or you need to pass the width, height to the object when it's created Board b(width, height); or you can place the initialization of board into initialization list of ConnectFour


ConnectFour::ConnectFour() :
b(7,6)
{
}

so that it has the info needed when ConnectFour is created.

Finally, you could keep a pointer to the Board object in the parent class and dynamically create it in the parent class's constructor. This requires more care and probably use of smart pointers to handle the creation and destruction of the object properly.

I'm guessing something like this

class board
{
public:
    board::board(int w,int h)
    {
        w = 0;
        h = 0;
    }
};

class connectFour
{
    connectFour::connectFour(int, int)
    {
        board b(7,9);
    }
};

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