class c++ 不存在默认构造函数

No default constructor exists for class c++

您好, 我试图用 std::string 变量 'name' 实例化一个匿名对象。但是 intellisenen 给我错误说

E0291   no default constructor exists for class "Player"    GoldGame    e:\C++ Projects\Hello World\GoldGame\GoldGame.cpp   17  

我提供了一个构造函数,它只能接受一个 std::string 变量,因为其他参数都提供了默认值。

你们能解释一下吗?

更让我困惑的是,当我改变

Player(name);

Player a(name);

或到

Player("test");

然后 intellisense 就完全没问题了。


GoldGame.cpp

#include "stdafx.h"
#include "Creature.h"
#include "Player.h"
#include <iostream>
#include <string>


int main()
{
    std::cout << "Enter your name: ";
    std::string name;
    std::cin >> name;

    Player(name);


    return 0;
}

Creature.h

#pragma once
#include <string>
class Creature
{
public:
    Creature(const std::string &name, const char symbol, const int health, const int damage, const int gold);
    ~Creature();

    //getters
    const std::string& getName() { return m_name; }
    const char getSymbol() { return m_symbol; }
    const int getHealth() { return m_health; }
    const int getDamage() { return m_damage; }
    const int getGold() { return m_gold; }

    //health, gold and dead 
    void reduceHealth(const int healthMinus);
    void addGold(const int gold);
    bool isDead();

private:
    std::string m_name;
    char m_symbol;
    int m_health;
    int m_damage;
    int m_gold;
};

Creature.cpp

#include "stdafx.h"
#include "Creature.h"




Creature::Creature(const std::string & name, const char symbol, const int health, const int damage, const int gold)
    :m_name(name), m_symbol(symbol), m_health(health), m_damage(damage), m_gold(gold)
{
}

Creature::~Creature()
{
}

void Creature::reduceHealth(const int healthMinus)
{
    m_health -= healthMinus;
}

void Creature::addGold(const int gold)
{
    m_gold += gold;
}

bool Creature::isDead()
{
    if (m_health>0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Player.h

#pragma once
#include "Creature.h"
#include <string>

class Player :
    public Creature
{
public:
    Player(const std::string &name, const char symbol='@', const int health=10, const int damage=1, const int gold=0);
    ~Player();
    const int getLevel() { return m_level; }
    void levelUp();
    bool hasWon();
private:
    int m_level;
};

Player.cpp

#include "stdafx.h"
#include "Player.h"




Player::Player(const std::string & name, const char symbol, const int health, const int damage, const int gold)
    :Creature(name,symbol,health,damage,gold)
{
}

Player::~Player()
{
}

void Player::levelUp()
{
    ++m_level;
}

bool Player::hasWon()
{
    if (m_level>=20)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Player(name); 并不像您认为的那样。它声明了一个类型为 Player 的新变量 name 并调用了默认构造函数。如果你想实例化一个匿名 Player 变量那么你需要写

(Player(name));
// or
Player{name}; // list initialization since C++11