c++继承和多态性

C++ inheritance/polymorphism

本文关键字:多态性 继承 c++      更新时间:2023-10-16
    #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类中正确执行此操作。

比较swordgun的构造函数。具体来说,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;
}