gpt4 book ai didi

c++ - 在 C++ 中确定继承对象的类型

转载 作者:太空宇宙 更新时间:2023-11-04 13:40:33 25 4
gpt4 key购买 nike

我有这两个类。

class ChessPiece
{
public:
ChessPiece();
virtual bool move() = 0;

};

class Bishop: public ChessPiece
{
public:
Bishop();
bool move();
};

在我这样创建 ChessPiece 之后,我正在尝试确定它的类型

ChessPiece* foo = new Bishop()

我正在尝试获取 foo(Bishop)的类型,而不是 ChessPiece

谢谢

最佳答案

好吧,有一些方法可以做到这一点,看看动态转换:

class A
{
public:
virtual void Foo() = 0;
};

class B : public A
{
public:
void Foo() { }
};

void Test()
{
A* bar = new B();
if (B* test = dynamic_cast<B*>(bar))
{
// use test here
}
delete bar;
}

或者,您可以在定义棋子 ID 的棋子类中存储一个枚举。

关于c++ - 在 C++ 中确定继承对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27799924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com