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

标签 c++ class oop object cout

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

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

关于C++ 输出对象中的所有成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213902/

相关文章:

java - “找不到或加载主类”是什么意思?

php - 在 PHP 中访问同级 (?) 变量

html - BEM CSS类命名

c# - 适配包含 ref 参数的 C# 事件

oop - 领域驱动设计 : Is a Subdomain a class?

c++ - 部分特化结构与重载函数模板

c++ - 用于创建锁层次结构的实用程序?

c++ - Ubuntu 上的 Qt 5.1.1 编译器设置

c++ - 更优雅的方法来检查 C++ 数组中的重复项?

Java : How to create an object in a method and use it throughout the class?