构造函数参数

时间:2013-04-30 14:39:02

标签: c++

Player.h

#ifndef HEADER_GUARD_PLAYER
#define HEADER_GUARD_PLAYER

#include <string>
using std::string;


//Parent player class
class Player
{
      private:        
      protected:
         string playerName; 
         int chipCount;

      public:
         //Constructor
         Player();
         Player(string name);

}; 

//Custom Players

class PlayerSteven: public Player
{
};
class PlayerBlake: public Player
{
};
class PlayerTucker: public Player
{
};
#endif

Player.cpp

#include "Player.h"
#define STARTCHIPS 1500

Player::Player()
{
     chipCount = STARTCHIPS;
     playerName = "Default";          
};
Player::Player(string name)
{
     playerName = name;
};

Main.cpp的

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

using namespace std;

int main()
{
    Deck deck;
    PlayerSteven steven = new PlayerSteven("Steven");
    PlayerBlake blake = new PlayerBlake("Blake");
    PlayerTucker tucker = new PlayerTucker("Tucker");

    deck.shuffle();
    int x = 0;
    int y = 0;
    for (int i = 0; i < 52; i++)
    {
        deck.nextCard(x,y);
        cout << x << "," << y << endl;
    }
    system("PAUSE");
    return 0;
}

错误:

11 C:\ Users \ Documents \ temp \ p_comp.cpp没有匹配函数来调用`PlayerSteven :: PlayerSteven(const char [7])'

11 C:\ Users \ Documents \ temp \ p_comp.cpp没有匹配函数来调用`PlayerSteven :: PlayerSteven(const char [7])'

注意C:\ Dev-Cpp \ PROJECTS \ Player.h:26 PlayerSteven :: PlayerSteven(const PlayerSteven&amp;)

任何人都知道如何编译它?

感谢。

2 个答案:

答案 0 :(得分:2)

在C ++中,构造函数不是继承的。所以你必须在子类中添加它们:

class PlayerSteven: public Player
{
public:
    PlayerSteven()
    {}
    PlayerSteven(string name)
    :Player(name)
    {}
};

Player的其他子类也一样。

如果你有一个最近的C ++ 11编译器,你实际上可以继承构造函数,但你必须明确地这样做:

class PlayerSteven : public Player
{
public:
    using Player::Player;
};

答案 1 :(得分:1)

您需要为派生类型声明和定义构造函数:

class PlayerSteven: public Player
{
  PlayerSteven() {}
  PlayerSteven(const std::string& s) : Player(s) {}
};

等等。在C ++ 11中,您可以使用inherited constructors

class PlayerSteven: public Player
{
  using Player::Player;
};

接下来,在您的主要内容中,您尝试从指向PlayerSteven的指针初始化PlayerSteven对象:

PlayerSteven steven = new PlayerSteven("Steven");

您没有构造函数来执行此类转换,您可能无论如何都不想要这样做。您可以实例化PlaverSteven对象:

PlayerSteven steven("Steven");