gpt4 book ai didi

类中的 C++ 列表以存储用户输入

转载 作者:行者123 更新时间:2023-11-30 05:28:43 24 4
gpt4 key购买 nike

自从我上次编写代码以来已经有一段时间了,但我正在努力重温我在学习期间获得的少数技能。现在,我只是想对我在网上看到的陈述/问题实现解决方案。

为此,我尝试构建一个过敏类,用于存储用户输入提供的信息(类别、名称、症状)。我一开始只是为每个参数输入字符串,但在现实世界中,人们可能有多种症状。为此,我想为症状创建一个列表参数而不是单个字符串。这是我的文件:

过敏.hpp:

    #ifndef Allergy_hpp
#define Allergy_hpp

#include <iostream>
#include <string>
#include <list>
using namespace std;


class Allergy {
public:

Allergy();
Allergy(string, string, list <string>);
~Allergy();

//getters
string getCategory() const;
string getName() const;
list <string> getSymptom() const;


private:

string newCategory;
string newName;
list <string> newSymptom;
};

#endif /* Allergy_hpp */

过敏.cpp:

#include "Allergy.hpp"

Allergy::Allergy(string name, string category, list <string> symptom){
newName = name;
newCategory = category;
newSymptom = symptom;
}

Allergy::~Allergy(){

}

//getters

string Allergy::getName() const{
return newName;
}

string Allergy::getCategory() const{
return newCategory;
}


list Allergy::getSymptom() const{
return newSymptom;
}

主要.cpp:

#include <iostream>
#include <string>
#include "Allergy.hpp"

using namespace std;



int main() {
string name;
string category;
string symptom;

cout << "Enter allergy name: ";
getline(cin, name);
cout << "Enter allergy category: ";
getline(cin, category);
cout << "Enter allergy symptom: ";
getline(cin, symptom);

Allergy Allergy_1(name, category, symptom);
cout << endl << "Allergy Name: " << Allergy_1.getName() << endl <<
"Allergy Category: " << Allergy_1.getCategory() << endl <<
"Allergy Symptom: " << Allergy_1.getSymptom() << endl;

return 0;
}

我还没有在 main.cpp 中实现它。现在我一直在为 Allergy.cpp 中的列表创建一个 getter。非常感谢任何指导!!!

最佳答案

getter 实现的签名与类定义中的签名不匹配:

list Allergy::getSymptom() const{  // <===  oops!!
return newSymptom;
}

只需更正此:

list<string> Allergy::getSymptom() const{  // <===  yes !!
return newSymptom;
}

编辑:

即使 getter 现在可以编译,您也不能像这样显示症状列表:

cout << endl << "Allergy Name: " << Allergy_1.getName() << endl <<
"Allergy Category: " << Allergy_1.getCategory() << endl <<
"Allergy Symptom: " << Allergy_1.getSymptom() << endl;

要打印症状,请使用 range-for,这是遍历列表的一种简单方法:

for (auto& s : Allergy_1.getSymptom()) {
cout << s<<" ";
}

或者使用带有 ostrea_iterator 的拷贝:

auto mylist=Allergy_1.getSymptom(); 
copy (mylist.begin(), mylist.end(), ostream_iterator<string>(cout," "));

关于类中的 C++ 列表以存储用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36679953/

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