C ++-没有适当的默认构造函数 [英] C++ - No appropriate default constructor available
问题描述
我在使用一个非常简单的程序时遇到了麻烦。它将引发错误:
I'm having trouble with a very simple program. It throws the errors:
错误C2512:播放器:没有合适的默认构造函数
IntelliSense: Player类不存在默认构造函数
I感觉这与在Game.h中将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
Player.cpp
#include "Player.h"
#include <iostream>
using namespace std;
Player::Player(int walletAmount)
{
wallet = walletAmount;
}
Player::~Player(void)
{
}
推荐答案
与C#相反,此声明;
In contrast to C#, this declaration;
Player player;
...是 Player $ c $类型的实例化c>,这意味着到您在构造函数中分配它时,它已经构造为没有参数。
...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.
您需要做的是告诉该类如何初始化 player
在您附加到构造函数标头的初始化列表中;
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)
{
...
...告诉编译器首先使用该构造函数初始化 player
首先使用默认的无参数构造函数,然后然后为其赋值。
...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.
这篇关于C ++-没有适当的默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!