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

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

07-24 09:45
查看更多