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

时间:2016-04-17 17:42:26

标签: c++ list class parameters getter

自从我上次编写代码以来已经有一段时间了,但是我试图抹去我在学习期间获得的一些技能。就目前而言,我只是试图实现我在网上看到的陈述/问题的解决方案。

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

Allergy.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 */

Allergy.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;
}

main.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。非常感谢任何指导!

1 个答案:

答案 0 :(得分:1)

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;

要打印症状,请使用范围,这是迭代列表的简单方法:

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

或者使用带有ostrea_iterator的副本:

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