C++ - No appropriate default constructor available

2019-05-09 11:01发布

问题:

This question already has an answer here:

  • “No appropriate default constructor available”--Why is the default constructor even called? 2 answers

I'm having trouble with a very simple program. It throws the errors:

error C2512: 'Player' : no appropriate default constructor available

IntelliSense: no default constructor exists for class "Player"

I have a feeling it's got something to do with declaring the Player class as a private variable in the Game.h but I can't see why. Any help would be much appreciated.

Game.h

#pragma once
#include "Player.h"

class Game
{
public:
    Game(void);
    void start(void);
    ~Game(void);
private:
    Player player;
};

Game.cpp

#include "Game.h"

Game::Game(void)
{
    Player p(100);

    player = p;
}

void Game::start()
{
    ...
}

Game::~Game(void)
{
}

Player.h

#pragma once
class Player
{
public:
    Player(int);
    ~Player(void);

private:
    int wallet;
};

Player.cpp

#include "Player.h"
#include <iostream>

using namespace std;

Player::Player(int walletAmount)
{
    wallet = walletAmount;
}

Player::~Player(void)
{
}

回答1:

In contrast to C#, this declaration;

Player player;

...is an instantiation of the type Player, which means that by the time you're assigning it inside the constructor, it has already been constructed without a parameter.

What you need to do is to tell the class how to initialize player in what is called an initializer list that you append to the constructor header;

Game::Game(void) : player(100)
{
...

...which tells the compiler to use that constructor to initialise player in the first place instead of first using the default no-parameter constructor and then assigning to it.



回答2:

When you construct instance of Game, it tries to construct its member player using the default constructor. Initialize player within the initializer list, not inside the body of constructor:

Game::Game() : player(100)
{
    ...
}


回答3:

Only Player::Player(int) exists, so you need to initialize player in Game::Game()

Game::Game(void)
    : player( 100 )
{
}


回答4:

In general - not in this case - the error

no appropriate default constructor available

may also occur, if you forgot to include the header file for the related object.

This happened to me, so I wanted to add this solution here.