继承 c++儿童家长
我有一个简单的问题:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是切片。
Uzi
是一种武器
,但反之则不然。您可以为此使用指针:此外,您还会收到错误,因为
Weapon()
类中没有Shot()
方法。您可能希望将其声明为虚拟的,并使其抽象(可选)。您将其设为
虚拟
以允许多态性。这样:
将调用
Uzi
类中的Shot()
,尽管它是在Weapon
指针上调用的。以下应该有效:
This is slicing.
Uzi
is-aWeapon
, but not the other way around. You can use pointers for this:Also, you get the error because there is no
Shot()
method in theWeapon()
class.You might want to declare it
virtual
and also make it abstract (optional). You make itvirtual
to allow polymorphism.That way:
will call
Shot()
in theUzi
class, although it's called on aWeapon
pointer.The following should work:
您忘记在
Weapon
类中声明void Shot(float angle)
。You forgot to declare
void Shot(float angle)
in theWeapon
class.对于多态性,需要将方法虚拟化,Weapon 应该声明:
然后每个子类都应该实现虚拟方法。
编辑:哦,你不能只将构造函数分配给彼此,你需要实例化一个具体的子类,即:
如其他几个答案中提到的。
For polymorphism, you need to virtualise the method, Weapon should declare:
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:
as mentioned in several other answers.