1
#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.

有人可以通过修复我的代码来帮忙吗?我真的不明白我做错了什么,提前谢谢!

4

5 回答 5

4

问题在这里:

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

因为此方法的返回值未定义,并且您试图将值附加intstd::stringwith +,这是不可能的。由于您需要比附加字符串更复杂的输出格式,因此您可以使用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) { }
于 2013-09-25T06:22:51.247 回答
2

您的get函数需要返回类型。此外,在 C++ 中,您不能只是将+字符串和其他对象随意组合在一起。尝试使用 astd::stringstream代替,它可以让您输入字符串、数字等:

string get() {
    basic_stringstream ss;
    ss << endl
       << "Name: " << name << endl
       << "Age: " << age << endl
       << "Gender: " << gender << endl;
    return ss.str();
}

您需要#include <sstream>在顶部添加一个。

于 2013-09-25T06:23:44.093 回答
2

您不能将 int 类型(年龄)添加到字符串类型(姓名、性别)。首先将年龄转换为字符串。

检查C++ 连接字符串和 int

于 2013-09-25T06:24:28.697 回答
2

您的代码中有 2 个错误。

1.您没有在 get 方法中使用返回值作为字符串。2.你不能直接添加字符串和整数。

检查如何在此处添加字符串和 int

于 2013-09-25T06:27:50.507 回答
1

我不确定,但我认为这是因为您的get()函数没有声明返回类型。应该是string get()。话虽如此,对于这样的错误来说,这是一个奇怪的错误消息。

于 2013-09-25T06:22:47.337 回答