我有3個C++文件,instrument.h, percussion.h, and instrumentApp.cpp
。 Instrument.h
是基類,percussion.h
繼承它。 Percussion
對象在instrumentApp.cpp
類中定義和實現。每當我運行instrumentApp.cpp
時,我都會遇到分段錯誤錯誤。在C++中無法找到段錯誤錯誤
我已經設法追查錯誤的原因,以函數中的超載<< operator
函數,我在這裏調用基類instrument.h
的方法。出於某種原因,我的代碼無法調用基類的方法,我不知道爲什麼。你能幫我麼?
這裏是instrument.h類
#ifndef INSTRUMENT_H
#define INSTRUMENT_H
class Instrument{
private:
std::string name;
std::string sound;
std::string lowRange;
std::string highRange;
public:
Instrument(std::string name, std::string sound, std::string lowRange, std::string highRange){
this->name = name;
this->sound = sound;
this->lowRange = lowRange;
this->highRange = highRange;
}
std::string getName() const{
return this->name;
}
std::string play()const {
return this->sound;
}
std::string getLowRange() const{
return this->lowRange;
}
std::string getHighRange() const{
return this->highRange;
}
bool isWind();
bool isWoodWind();
bool isBrass();
bool isKeyboard();
bool isPercussion();
bool isStrings();
friend std::ostream &operator <<(std::ostream &os, const Instrument &instrument){
}
};
#endif
這裏是percussion.h類
#ifndef PERCUSSION_H
#define PERCUSSION_H
#include "instrument.h"
class Percussion : public Instrument{
private:
bool struck;
public:
Percussion(std::string name, std::string sound, std::string lowRange, std::string highRange, bool struck) : Instrument(name,sound,lowRange,highRange){
this->struck=struck;
}
bool isStrucked() const {
return this->struck;
}
bool isPercussion() {
return true;
}
std::string getType() const{
if(this->struck){
return "struck";
}
else{
return "";
}
}
friend std::ostream &operator <<(std::ostream &os, Percussion &percussion){
//The error stems from this line of code
//Apparently, the getName() method in the base class isn't called
os<<percussion.getName();
}
};
#endif
這裏是實現文件instrumentApp.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include "instrument.h"
#include "percussion.h"
#include "strings.h"
using namespace std;
int main() {
Percussion timpani("timpani", "boom", "D2", "A2", true);
cout << timpani << endl;
Percussion harp("harp", "pling", "Cb1", "F#7", false);
cout << harp << endl;
return 0;
}
我很驚訝這甚至編譯,因爲你沒有從你的'運營商返回任何如下<<'在任一類 – pat
...這是正是這個問題。 –
我在percussion.h類 – Avi