对象切片:从基类对象

时间:2016-03-28 16:33:57

标签: c++ oop inheritance object-slicing

  
    

修改

  
     
      
  1. 问题出在 GoFish.h 文件中,在构造函数中   具体而言,它试图实例化玩家对象。

  2.   
  3. 编译器抛出以下错误消息:没有名为' noOfBooks'在'播放器'

  4.   
GoFish() {players = new GoFishPlayer[2];} // Instantiate two players
对于初学者来说,

对象切片似乎是OOP中最模糊的概念之一。我一直在用C ++开发这个卡片游戏,我有一个名为 Player 的基类和一个名为 GoFishPlayer 的派生类。当尝试访问引用回Player对象的GoFishPlayer对象的方法时,程序倾向于切除派生类的特定方法和属性,从而使其成为基础对象的克隆。有没有办法克服这个问题?

  

Game.h

     
    

抽象类游戏:它构成了两个游戏的基础 -     GoFish和CrazyEights

  
class Game {

protected:
Deck* deck;
Player* players;
int player_id;

public:
Game(){
    deck = Deck::get_DeckInstance(); // Get Singleton instance
    player_id = choosePlayer();
    players = NULL;
}
....
}
  

GoFish.h

     
    

派生类GoFish - 当我试图实例化从游戏类派生的Player对象时,问题出现在构造函数中

  
class GoFish : public Game{

static GoFish* goFish;
GoFish() {players = new GoFishPlayer[2];} // Instantiate two players

public:
static GoFish* get_GoFishInstance() {
    if(goFish == NULL)
        goFish = new GoFish();

    return goFish;
}
  

Player.h

class Player{

protected:
std::string playerName;
Hand hand;
bool win;

public:
Player(){ 
    playerName = "Computer"; // Sets default AI name to Computer
    hand = Hand(); // Instatiate the hand object
    win = false;
}
....
  

GoFishPlayer.h

class GoFishPlayer : public Player {

private:
std::vector <int> books;
int no_of_books;

public:
GoFishPlayer() {
    no_of_books = 0;
    books.resize(13);
}

int noOfBooks(){return no_of_books;}
void booksScored() {no_of_books++;}

bool checkHand() {}
....

1 个答案:

答案 0 :(得分:0)

您的问题的措辞对我来说似乎含糊不清但最好我理解您通过引用data comp; input a b; flag = ifn(b NE 2*a,1,0); cards; 2 4 1 2 3 5 ;;;; run; proc means n mean sum; var flag; run; 对象尝试访问GoFishPlayer的方法?这不是由对象切片引起的问题,而是多态性的工作原理。

您需要强制转换Player对象的引用,以使其成为对Player对象的引用。

GoFishPlayer

仅当您确定知道class Parent { public: void foo() { std::cout << "I'm a parent" << std::endl; } }; class Derived : public Parent { public: void bar() { std::cout << "I'm a derived" << std::endl; } }; int main() { Derived d; // reference to a derived class stored as a prent reference // you can't access derived methods through this Parent& p_ref = d; // this won't work // p_ref.bar(); Derived& d_ref = static_cast<Derived&>(p_ref); // this works d_ref.bar(); } 实际上属于p_ref类型,或者它属于从Derived继承的类型时才有效。如果您无法确定是否需要使用Derived进行运行时检查,然后捕获所引发的任何dynamic_cast异常。