这段代码运行时显示munmap_chunk(): invalid pointer,应该怎么修改?#include<iostream> #include<string> using namespace std; class Creature { public: Creature(const int& hands, const int& legs):_hands(hands),_legs(legs) {cout << "A Creature has been created!" << endl; cout << "It has " << hands << " hand(s)!" << endl; cout << "It has " << legs << " leg(s)!" << endl;} ~Creature() {cout << "Creature object exiled!" << endl;} int GetHands() const {return _hands;} int GetLegs() const {return _legs;} private: int _hands; int _legs; }; class Beast:virtual public Creature { public: Beast(const int& hands, const int& legs, const string& name) :Creature(hands,legs),_name(name){cout << "Its beast name is " << _name << endl;} ~Beast() {cout << "Beast object exiled!" << endl;} string GetName() const {return _name;} private: string _name; }; class Human:virtual public Creature { public: Human(const int& hands, const int& legs, const string& name):Creature(hands,legs),_name(name) {cout << "Its human name is " << _name << endl;} ~Human() {cout << "Human object exiled!" << endl;} string GetName() const {return _name;} private: string _name; }; class Orc:public Human,public Beast { public: Orc(const int& hands, const int& legs, const string& beast_name, const string& human_name):Creature(hands, legs),Beast(hands,legs,beast_name),Human(hands,legs,human_name){} ~Orc() {cout << "Orc object exiled!" << endl;} string GetBeastName() const {return Beast::GetName();} string GetHumanName() const {return Human::GetName();} };
时间: 2024-02-01 09:16:06 浏览: 128
这段代码中存在一个 Diamond 继承问题,即 Orc 类同时继承了 Human 和 Beast 类,而这两个类又都继承了 Creature 类,导致 Orc 类中存在两份 Creature 对象。为了解决这个问题,可以将 Creature 类的继承方式改为虚继承,即在 Creature 类继承声明中加上 virtual 关键字:
```
class Beast : virtual public Creature {
public:
Beast(const int& hands, const int& legs, const string& name) :Creature(hands,legs),_name(name){
cout << "Its beast name is " << _name << endl;
}
~Beast() {
cout << "Beast object exiled!" << endl;
}
string GetName() const {return _name;}
private:
string _name;
};
class Human : virtual public Creature {
public:
Human(const int& hands, const int& legs, const string& name):Creature(hands,legs),_name(name) {
cout << "Its human name is " << _name << endl;
}
~Human() {
cout << "Human object exiled!" << endl;
}
string GetName() const {return _name;}
private:
string _name;
};
class Orc : public Human, public Beast {
public:
Orc(const int& hands, const int& legs, const string& beast_name, const string& human_name)
:Creature(hands, legs), Beast(hands,legs,beast_name), Human(hands,legs,human_name) {}
~Orc() {
cout << "Orc object exiled!" << endl;
}
string GetBeastName() const {return Beast::GetName();}
string GetHumanName() const {return Human::GetName();}
};
```
另外,如果该程序还是出现 munmap_chunk(): invalid pointer 错误,可能是由于其他部分的代码引起的内存错误,需要进一步排查。
阅读全文