#include <iostream>
#include <string>

using namespace std;

class Person{
    public:
        Person(string n, int a, string g) {
            setName(n);
            setAge(a);
            setGender(g);
        }
        void setName(string x) {
            name = x;
        }
        void setAge(int x) {
            age = x;
        }
        void setGender(string x) {
            gender = x;
        }
        get() {
            return "\nName: " + name + "\nAge: " + age + "\nGender: " + gender + "\n";
        }
    private:
        string name;
        int age;
        string gender;
};


int main() {

    return 0;
}

那就是我的代码,我要做的就是用构造函数创建一个基础类,并使用三个参数定义名称,年龄和性别,出于某种原因,当我尝试运行此命令以检查一切是否正常时,我得到错误说明(第23行):类型'const __gnu_cxx::__ normal_iterator不匹配。

有人可以帮我解决我的代码吗?我真的不明白我做错了什么,谢谢!

最佳答案

问题在这里:

public:
    ...
    get() {
        return "\nName: " + name + "\nAge: " + ... + gender + "\n";
    }

因为未定义此方法的返回值,并且您尝试使用intstd::string的值附加到+,所以这是不可能的。由于您不仅需要附加字符串,还需要更复杂的输出格式,因此可以使用std::ostringstream:
public:
    ...
    std::string get() {
        std::ostringstream os;
        os << "\nName: " << name << "\nAge: " << ... << gender << std::endl;
        return os.str();
    }

只是不要忘记#include <sstream>
边注:
Person(string n, int a, string g) {
    setName(n);
    setAge(a);
    setGender(g);
}

Person类中,您可以直接访问private成员:
Person(string n, int a, string g) : name(n), age(a), gender(g) { }

关于c++ - 我的 'Person'类怎么了?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18997576/

10-11 22:38
查看更多