C++输出对象中的所有成员
C++ output all members in a object
到目前为止,我已经定义了一个简单的类...
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
(。
相关文章:
- c++ 将成员函数的输出写入文本文件
- C++具有模板成员变量的类. 和参数内存输出
- 如何调试输出指向成员的指针
- 为什么当类的数据成员更改为引用时输出不同
- 如何从doxygen输出中排除类的无证件成员函数/变量
- C++输出对象中的所有成员
- 具有类构造函数和类成员变量的意外输出值
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- 将非零矢量成员读取为阵列和输出点产品
- 在数据拼接 C++ 时输出成员变量
- 覆盖运算符<< 对于控制台输出不适用于成员变量
- 正在输出类型向量的成员类型
- 在Rcpp中初始化NumericMatrix类成员后未收到的输出
- C++子级在复制构造函数和输出之间的某个时间点更改父成员
- 要写入输出迭代器的模板成员函数
- 当传入具有std::string成员的结构时,C++-gdb会给出意外的输出
- 重载运算符<<输出地址而不是数据成员
- 当我们对没有任何数据成员的类的对象使用sizeof运算符时.那么输出会是什么
- 在std::for_each中对成员函数的输出进行迭代
- 重载运算符<<在不使用友元函数的情况下输出对象成员