【问题标题】:C++ output all members in a objectC++ 输出对象中的所有成员
【发布时间】:2017-04-04 17:29:14
【问题描述】:

到目前为止,我已经定义了一个简单的类...

class person {
public:
    string firstname;
    string lastname;
    string age;
    string pstcode;
};

...然后将一些成员和值添加到名为“bill”的对象...

int main() {
    person bill;
    bill.firstname = "Bill";
    bill.lastname = "Smith";
    bill.age = "24";
    bill.pstcode = "OX29 8DJ";
}

但是您将如何简单地输出所有这些值?您会使用 for 循环遍历每个成员吗?

【问题讨论】:

  • 好吧,你可以为你的班级重载operator <<。
  • 简单地定义。您不能遍历它们,因为成员字段不是数组。不过你可以重载operator<<。
  • c++ 没有本机反射,因此您必须手动“迭代”类的成员。(某些库允许某种反射)。
  • 为什么age 是一个字符串?通常,age 是一个无符号整数变量(无符号,因为您不能有负年龄)。
  • @ThomasMatthews:我的年龄是“大于我姐姐的年龄”或“取决于或当前日期”;-)。

标签: c++ class oop object cout


【解决方案1】:

我通常会覆盖 operator <<,以便我的对象与任何内置对象一样易于打印。

这是覆盖operator <<的一种方法:

std::ostream& operator<<(std::ostream& os, const person& p)
{
    return os << "("
              << p.lastname << ", "
              << p.firstname << ": "
              << p.age << ", "
              << p.pstcode
              << ")";
}

然后使用它:

std::cout << "Meet my friend, " << bill << "\n";

这是一个使用这种技术的完整程序:

#include <iostream>
#include <string>

class person {
public:
    std::string firstname;
    std::string lastname;
    std::string age;
    std::string pstcode;
    friend std::ostream& operator<<(std::ostream& os, const person& p)
    {
        return os << "("
                  << p.lastname << ", "
                  << p.firstname << ": "
                  << p.age << ", "
                  << p.pstcode
                  << ")";
    }

};

int main() {
    person bill;
    bill.firstname = "Bill";
    bill.lastname = "Smith";
    bill.age = "24";
    bill.pstcode = "OX29 8DJ";

    std::cout << "Meet my friend, " << bill << "\n";
}

【讨论】:

    【解决方案2】:

    简单地说,您使用ostream 输出每个元素:

    class Person
    {
    public:
        void Print_As_CSV(std::ostream& output)
        {
           output << firstname << ",";
           output << lastname  << ",";
           output << age       << ",";
           output << pstcode   << "\n";
        }
        string firstname;
        string lastname;
        string age;
        string pstcode;
    };
    

    可能有不同的打印方法,这就是我没有重载operator &lt;&lt;的原因。例如,每行一个数据成员将是另一种流行的场景。

    编辑 1:为什么不循环播放?
    class 具有单独的字段,这就是您不能遍历成员的原因。

    如果你想迭代或循环成员,你要么必须为你的类有一个迭代器,要么使用提供迭代的容器,例如std::vector。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-03
      相关资源
      最近更新 更多