0%

C++打印结构体的方法

通常在 C++ 语言中,我们无法直接对结构体打印,但是可以通过某种方式来打印结构体。

使用友元函数打印

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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;
}

使用宏定义简化定义流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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);
};