对象切片:从基类对象访问分层的类方法
Object Slicing : Access dervied class methods from base class object
编辑:
问题出现在GoFish.h文件中,在构造函数中具体地说,它试图实例化players对象。
编译器抛出以下错误消息:在"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
异常。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 如何创建具有分层对象和值的 json 对象
- 对象切片:从基类对象访问分层的类方法