继承 c++儿童家长

发布于 2025-01-05 11:53:30 字数 481 浏览 3 评论 0原文

我有一个简单的问题:

class Weapon{
public:
    int dmg;
    float speed;
    int rate;
};

class Uzi : public Weapon{
public:
    Uzi();
    void Shot(float angle);
};

Class Pistol : public Weapon{
public:
    Pistol();
    void Shot(float angle);
};

稍后在代码中,当我保留时,例如:

Weapon wep;
wep = Uzi;
wep.Shot(15); 

它不起作用: 对“Weapon::Shot(float)”的未定义引用

我可以保留不同类型的“wep”变量吗? 我认为不会,因为武器正在发生变化(手枪/乌兹冲锋枪/...)。

提前致谢!

I have simple problem:

class Weapon{
public:
    int dmg;
    float speed;
    int rate;
};

class Uzi : public Weapon{
public:
    Uzi();
    void Shot(float angle);
};

Class Pistol : public Weapon{
public:
    Pistol();
    void Shot(float angle);
};

Later in code when I reserve for example:

Weapon wep;
wep = Uzi;
wep.Shot(15); 

It doesn't work:
undefined reference to `Weapon::Shot(float)'

Can I reserve different type of 'wep' variable?
I think no because weapons are changing(pistol/uzi/...).

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

怕倦 2025-01-12 11:53:30
Weapon wep;
wep = Uzi;

这是切片。 Uzi 是一种武器,但反之则不然。您可以为此使用指针:

Weapon* wep = new Uzi();

此外,您还会收到错误,因为 Weapon() 类中没有 Shot() 方法。

您可能希望将其声明为虚拟的,并使其抽象(可选)。您将其设为虚拟以允许多态性。

这样:

Weapon* wep = new Uzi();
wep->Shot();

将调用 Uzi 类中的 Shot(),尽管它是在 Weapon 指针上调用的。

以下应该有效:

class Weapon{
public:
    int dmg;
    float speed;
    int rate;
    virtual void Shot(float angle) {}; //move implementation to cpp file
};
Weapon wep;
wep = Uzi;

This is slicing. Uzi is-a Weapon, but not the other way around. You can use pointers for this:

Weapon* wep = new Uzi();

Also, you get the error because there is no Shot() method in the Weapon() class.

You might want to declare it virtual and also make it abstract (optional). You make it virtual to allow polymorphism.

That way:

Weapon* wep = new Uzi();
wep->Shot();

will call Shot() in the Uzi class, although it's called on a Weapon pointer.

The following should work:

class Weapon{
public:
    int dmg;
    float speed;
    int rate;
    virtual void Shot(float angle) {}; //move implementation to cpp file
};
国产ˉ祖宗 2025-01-12 11:53:30

您忘记在 Weapon 类中声明 void Shot(float angle)

You forgot to declare void Shot(float angle) in the Weapon class.

嘿咻 2025-01-12 11:53:30

对于多态性,需要将方法虚拟化,Weapon 应该声明:

virtual void Shot(float angle) = 0;

然后每个子类都应该实现虚拟方法。

编辑:哦,你不能只将构造函数分配给彼此,你需要实例化一个具体的子类,即:

Weapon *weapon = new Uzi();

如其他几个答案中提到的。

For polymorphism, you need to virtualise the method, Weapon should declare:

virtual void Shot(float angle) = 0;

and then each subclass should implement the virtual method.

Edit: Oh, and you can't just assign constructors to one another, you need to instantiate a concrete subclass, i.e:

Weapon *weapon = new Uzi();

as mentioned in several other answers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文