类构造函数问题

时间:2016-03-22 07:09:52

标签: c++

我目前正在编写一个C ++单人游戏,命令行,二十一点游戏。我遇到的主要问题是每当我的Player类默认构造函数时,

    Player(const std::string& name = "");
构造

,即使有来自命令行的输入来指定名称,它似乎也是默认的。

我的经销商类默认构造函数似乎工作正常,因为未初始化为像我的Player类一样的空字符串。

    Dealer(const std::string& name = "Dealer");

似乎我的代码完全忘记了输入中用于玩家姓名的数据。

我尽可能地缩小代码以找到问题,但我还没有找到解决方案。 没有编译错误,但我的播放器名称没有显示。

// ConsoleApplication2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <vector>
#include <algorithm>

class Player
{
public:
    Player(const std::string& name = "");
    virtual ~Player();
    friend std::ostream& operator <<(std::ostream& str, const Player& aPlayer);
protected:
    const std::string m_Name;
};

Player::Player(const std::string& m_name) : m_Name(m_name) {}
Player::~Player() {}

class Dealer : public Player
{
public:
    Dealer(const std::string& name = "Dealer");
    virtual ~Dealer();
};

Dealer::Dealer(const std::string& name) : Player(name) {}
Dealer::~Dealer() {}

class Game 
{
public:
    Game(const std::string& name);
    ~Game();
    void Play();
protected:
    Player newPlayer;
};

Game::Game(const std::string& name)
{
    srand(time(0));
    // I feel like something else needs to go here to initialize a player or something. Not sure what.

}
Game::~Game() {}

void Game::Play()
{
    std::cout << newPlayer << std::endl;
    // Possible this could be messing it up?
}

std::ostream& operator <<(std::ostream& str, const Player& aPlayer);

int main()
{
    std::cout << "Enter your name: ";
    std::string name;
    std::cin >> name;
    Game Game(name);
    Game.Play();
    return 0;
}

std::ostream& operator <<(std::ostream& str, const Player& aPlayer)
{
    str << aPlayer.m_Name << ":\t";

    return str;
}

当我在没有调试的情况下运行时,这是我的结果:

Enter your name: Dane
:
Dealer:
Press any key to continue . . .

我希望在第一次冒号之前得到一个名字(在这种情况下为Dane)并且它不想出现。我无法弄清楚我的代码中的问题,并想知道是否有人可以给我一些关于编码错误的见解。

3 个答案:

答案 0 :(得分:1)

Game构造函数中,您应该初始化Player对象newPlayer,并将参数传递给它(如何使用名称初始化newPlayer对象? )。

使用构造函数成员初始化列表执行此操作:

Game::Game(const std::string& name)
    : newPlayer(name)  // This is the member initializer list
{
    ...
}

参见例如this constructors and member initializer lists reference了解更多信息。

答案 1 :(得分:1)

您忘了将名字传递给您的播放器:

Game::Game(const std::string& name) :
    newPlayer(name)
{
    srand(time(0));
}

答案 2 :(得分:-1)

按如下方式定义您的Game类,不要在析构函数中清除pointer到Player

class Game 
{
public:
    Game(const std::string& name);
    ~Game();
    void Play();
protected:
    Player *newPlayer;
};

Game::Game(const std::string& name)
{
    srand(time(0));
    // I feel like something else needs to go here to initialize a player or something. Not sure what.
    this->newPlayer = new Player( name );
}


void Game::Play()
{
    std::cout << (*newPlayer) << std::endl;
    // Possible this could be messing it up?
}