到目前为止我已经定义了一个简单的类...
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/