gpt4 book ai didi

c++ - 无法在 C++ 中找到段错误

转载 作者:行者123 更新时间:2023-11-28 05:26:32 25 4
gpt4 key购买 nike

我有 3 个 C++ 文件,instrument.h, percussion.h, and instrumentApp.cpp . Instrument.h是基类,percussion.h继承它。 Percussion对象在 instrumentApp.cpp 中定义和实现类(class)。每当我跑instrumentApp.cpp ,我得到了段错误。

我已经设法将错误的原因追溯到重载的 << operatorpercussion.h 中发挥作用我在哪里调用基类的方法 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;
}

最佳答案

这里的问题是当我重载 << 运算符时我没有返回 os 对象。

percussion.h文件中修复如下

friend std::ostream &operator <<(std::ostream &os,  Percussion &percussion){

os<<percussion.getName();

return os;

}

关于c++ - 无法在 C++ 中找到段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40445492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com