【问题标题】:What is wrong with my 'Person' class?我的“人”类有什么问题?
【发布时间】:2013-09-30 14:40:45
【问题描述】:
#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.

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

【问题讨论】:

  • 你能指出哪一行是第23行吗?谢谢。

标签: c++ class


【解决方案1】:

问题就在这里:

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

因为此方法的返回值未定义,并且您尝试使用+int 的值附加到std::string,这是不可能的。由于您需要比附加字符串更复杂的输出格式,您可以使用std::ostringstream

public:
    ...
    std::string get() {
        std::ostringstream os;
        os << "\nName: " << name << "\nAge: " << ... << gender << std::endl;
        return os.str();
    }

别忘了#include &lt;sstream&gt;


旁注:

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) { }

【讨论】:

  • 他说using namespace std,所以不需要std::
  • @Dgrin91: using namespace std; 在全局范围内不是明智之举。
  • 但他做的却从来没有少过。更重要的是,这显然是作业代码,每个人都在作业中这样做。
  • @Dgrin91:你不应该这样做,即使是在家庭作业中。至少你会习惯std::前缀。
  • 这不是作业代码,我只是玩得开心,我从三月份开始学习javascript,上瘾,学习python,喜欢编程,现在我正在尝试学习C++,可能是我玩过的最有趣的事情了,(仅供参考,这段代码帮了很多忙!谢谢!):)
【解决方案2】:

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

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

您需要在顶部添加#include &lt;sstream&gt;

【讨论】:

    【解决方案3】:

    您的代码中有 2 个错误。

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

    查看如何添加字符串和int here

    【讨论】:

      【解决方案4】:

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

      查看C++ concatenate string and int

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 2023-01-14
          • 1970-01-01
          • 1970-01-01
          • 2021-11-16
          • 1970-01-01
          • 2017-10-02
          • 2018-12-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多