gpt4 book ai didi

c++ - 从基方法获取派生类

转载 作者:行者123 更新时间:2023-11-27 23:01:10 25 4
gpt4 key购买 nike

我有 3 个类 EntityCharacterItem。当我做的时候

Character * Player = new Character(QRectF(0, 0, 50, 50), "player", theScene);
Player->setVelocityX(30)->setAttackPoint(10);

编译器提示错误:'class Entity' 没有名为'setAttackPoint' 的成员。如何让 Entity* setVelocityX(qreal vx); 返回一个 Character 指针或一个 Item 指针?

.

class Entity : public QObject, public QGraphicsPolygonItem
{
Q_OBJECT

public:
Entity();
Entity(qreal x, qreal y, qreal w, qreal h, QString tag, QGraphicsScene *scene = 0, QGraphicsItem *parent = 0);
Entity(QRectF position, QString tag, QGraphicsScene *scene = 0, QGraphicsItem *parent = 0);
Entity(QString tag, QGraphicsScene *scene = 0, QGraphicsItem *parent = 0);
Entity* setVelocityX(qreal vx);
// etc
}


class Character : public Entity
{
Q_OBJECT

public:
Character(qreal x, qreal y, qreal w, qreal h, QString tag, QGraphicsScene *scene = 0, QGraphicsItem *parent = 0);
Character(QRectF position, QString tag, QGraphicsScene *scene = 0, QGraphicsItem *parent = 0);
Character(QString tag, QGraphicsScene *scene = 0, QGraphicsItem *parent = 0);
Character* setAttackPoint(int attackPoint);
//etc
}


class Item : public Entity
{
Q_OBJECT

public:
enum ItemType{
Consummable,
Special,
Weapon
};

Item(QString name, qreal x, qreal y, qreal w, qreal h, QString tag = "item", QGraphicsScene *scene = 0, Character *parent = 0);
Item* setOwner(Character* newOwner);
//etc
}

最佳答案

如果您完全确定类型(否则使用 dynamic_cast 并检查结果指针是否为非 nullptr):

reinterpret_cast< Character * >( Player->setVelocityX(30))->setAttackPoint(10)

此外,根据您的代码,您不能改用函数调用的顺序吗?

Player->setAttackPoint(10)->setVelocityX(30)

关于c++ - 从基方法获取派生类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27504717/

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