c++继承和多态性
C++ inheritance/polymorphism
#include<iostream>
using namespace std;
class weapon {
private:
int damage;
string name;
public:
weapon(const string& n, int d) {
name = n;
damage = d;
}
};
class sword : public weapon {
private:
int sharpness;
public:
sword(const string& n, int d, int s) : weapon(n,d), sharpness(s) {}
};
class gun : public weapon {
private:
int capacity;
public:
gun(const string& n, int d, int c) {
weapon(n,d);
capacity = c;
}
};
int main() {
sword s("Katana", 72, 41);
gun g("AK-47", 74, 30);
return 0;
}
在sword类中,sword函数在这个语法下工作得很好,但在gun类中,gun函数给我这个错误:没有匹配的函数调用武器:武器()
许多答案已经指出您希望使用基初始化式。但是,您也应该尽可能以相同的方式初始化成员,因此您的构造函数实际上应该是这样的:
gun(const string& n, int d, int c) : weapon(n, d), capacity(c) { }
…是的,在初始化器列表中进行所有初始化是完全正常的,所以actor的主体是空的(事实上,我通常更喜欢这样)。
你的gun
的构造函数应该使用初始化器列表来调用基构造函数。
gun(const string& n, int d, int c) : weapon(n,d){
capacity = c;
}
这是一个简单的打字错误。将火炮构造函数更改为
gun(const string& n, int d, int c) : weapon(n,d)
{
capacity = c;
}
。使用基类初始化器。您可以在sword
类中正确执行此操作。
比较sword
和gun
的构造函数。具体来说,gun’s如下
gun(const string& n, int d, int c) {
weapon(n,d);
capacity = c;
}
应该是
gun(const string& n, int d, int c): weapon(n.d) {
capacity = c;
}
我使用受保护的说明符和一个虚拟,这样您就可以用相同的函数方法显示两个对象的信息
#include<iostream>
using namespace std;
class weapon {
protected:
int damage;
string name;
public:
weapon(const string& n, int d) {
name = n;
damage = d;
}
void show_wep();
};
void weapon::show_wep()
{
cout << "damage: " << damage << endl
<< "name: " << name << endl;
}
class sword : public weapon {
protected:
int sharpness;
public:
sword(const string& n, int d, int s) : weapon(n,d), sharpness(s) {}
virtual void show_wep();
};
void sword::show_wep()
{
cout << "damage: " << damage << endl
<< "name: " << name << endl
<< "sharpness: " << sharpness << endl;
}
class gun : public weapon {
protected:
int capacity;
public:
gun(const string& n, int d, int c) : weapon(n,d), capacity(c) {}
virtual void show_wep();
};
void gun::show_wep()
{
cout << "damage: " << damage << endl
<< "name: " << name << endl
<< "capacity: " << capacity << endl;
}
int main() {
sword s("Katana", 72, 41);
gun g("AK-47", 74, 30);
s.show_wep();
cout << endl;
g.show_wep();
return 0;
}
相关文章:
- 继承/多态性 - 我是否被迫使用"protected"变量?
- 具有 3 级继承的基类shared_ptr的多态性
- C 中的多态性.在基类上调用继承的方法
- 模板、继承和多态性 C++
- 了解C++中的继承和多态性
- 继承多态性功能调用
- C++接口、继承、多态性
- 如何在保持多态性的同时,将成员函数添加到需要它的继承类中,而不会影响其他同级类?
- 在C++中使用多态性相对于继承的实际优势
- 收到未定义的引用错误 c++ 继承/多态性
- 多态性(继承)和价值类型
- 多种继承和多态性问题
- 如何正确组织继承类以利用多态性
- C++ 继承和多态性未知输出
- '<<'与继承和多态性超载?
- 在继承层次结构中将方法定义为虚拟方法一次,以使多态性发挥作用
- c++:多态性+多重继承顺序.继承顺序是否重要
- C++多重继承多态性
- 虚类成员函数的多态性/继承问题
- C++ 多态性 - 继承类的映射