C++输出对象中的所有成员

C++ output all members in a object

本文关键字:成员 输出 对象 C++      更新时间:2023-10-16

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

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 <<的一种方法:

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";
}

简单地说,您可以使用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 <<. 例如,每行一个数据成员将是另一种流行的方案。

编辑1:为什么不循环?
class具有单独的字段,这就是无法循环访问成员的原因。

如果要迭代或循环成员,则必须为类使用迭代器,或者使用提供迭代的容器(如 std::vector(。