对象切片:从基类对象访问分层的类方法

Object Slicing : Access dervied class methods from base class object

本文关键字:对象 分层 类方法 访问 基类 切片      更新时间:2023-10-16

编辑

  1. 问题出现在GoFish.h文件中,在构造函数中具体地说,它试图实例化players对象。

  2. 编译器抛出以下错误消息:在"Player"中没有名为"noOfBooks"的成员

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() {}
....

我觉得你的问题措辞不明确,但据我所知,你试图通过引用Player对象来访问GoFishPlayer的方法?这不是由对象切片引起的问题,这只是多态性的工作原理。

您需要强制转换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进行运行时检查,然后捕获抛出的任何std::bad_cast异常。