C++打印结构体的方法
通常在 C++ 语言中,我们无法直接对结构体打印,但是可以通过某种方式来打印结构体。
使用友元函数打印
class my_class
{
public:
int i;
std::string s;
friend std::ostream& operator<<(std::ostream& os, const my_class& obj)
{
return os << "i: " << obj.i << " s: " << obj.s;
}
};
int main()
{
my_class obj;
obj.i = 1;
obj.s = "hello";
std::cout << obj << std::endl;
return 0;
}
使用宏定义简化定义流程
#define FRIEND_STREAM_1(type, x1) \
friend std::ostream& operator<<(std::ostream& os, const type& type_obj) \
{ \
os << #type << ": this(" << &type_obj << "), "; \
os << #x1 << "(" << type_obj.x1 << ")"; \
return os; \
}
#define FRIEND_STREAM_2(type, x1, x2) \
friend std::ostream& operator<<(std::ostream& os, const type& type_obj) \
{ \
os << #type << ": this(" << &type_obj << "), "; \
os << #x1 << "(" << type_obj.x1 << "), "; \
os << #x2 << "(" << type_obj.x2 << ") "; \
return os; \
}
#define FRIEND_STREAM_3(type, x1, x2, x3) \
friend std::ostream& operator<<(std::ostream& os, const type& type_obj) \
{ \
os << #type << ": this(" << &type_obj << "), "; \
os << #x1 << "(" << type_obj.x1 << "), "; \
os << #x2 << "(" << type_obj.x2 << "), "; \
os << #x3 << "(" << type_obj.x3 << ") "; \
return os; \
}
class my_class
{
public:
int i;
std::string s;
FRIEND_STREAM_2(my_class, i, s);
};