用c++打印XMacro结构体到控制台中
Printing XMacro struct to the console with C++
我正在摆弄结构体和类,我看到了一个非常酷的编码,我想尝试一下:x-macro。
我的代码被分成3位,头,x-宏,和主要的cpp文件。程序还没有完成,还有代码覆盖和抛光要做,但是我正在尝试用x-宏构建一个结构体,然后我想把结构体的内容打印到屏幕上。
我的x-macro
#define X_AIRCRAFT
X(int, Crew)
X(int, SeatingCapacity)
X(int, Payload)
X(int, Range)
X(int, TopSpeed)
X(int, CargoCapacity)
X(int, FuelCapacity)
X(int, Engines)
X(int, Altitude)
X(double, mach)
X(double, Wingspan)
这是我的页眉(现在相当空白)
#include <iostream>
#include <string>
#ifndef X_AIRCRAFT
#include "xmacro.xmacro"
#endif // !
using namespace std;
typedef struct {
#define X(type, name) type name;
X_AIRCRAFT
#undef X
}Public_Airplane;
//Prototypes
void iterater(Public_Airplane *p_a);
这是我的main()
(我在这里剪掉了一堆代码。总之,我在这里所做的是构建一个具有不同属性的Airplane类。然后我构建了三个不同的子类,它们继承了Airplane的属性并做了它们自己的事情。所以我会尽量避免在网上发布这些课程,除非你们认为我的问题出在那里。我要做的就是发布不能正常工作的函数…)
#include <iostream>
#include <string>
#include <iomanip>
#include "aircraft.h"
#ifndef X_AIRCRAFT
#include "xmacro.xmacro"
#endif // !
using namespace std;
int main()
{
Public_Airplane p_a;
iterater(&p_a);
system("pause");
return 0;
}
void iterater(Public_Airplane *p_a)
{
//I want to print to screen the contents of my x-macro (and therefore my struct)
#define X(type, name) cout << "Value: = " << name;
X_AIRCRAFT
#undef X
}
我以前从来没有使用过宏,这就是为什么我现在试着这样做。但在我看来,预处理后的代码应该是这样的:
int crew;
int SeatingCapacity;
int Payload
int Range;
int TopSpeed;
int CargoCapacity;
int FuelCapacity;
int Engines;
int Altitude;
double mach;
double Wingspan;
cout << "Value: = " << Crew; (and so on down the list).
我做错了什么,使我无法获得上面的代码输出?
您最终希望生成如下所示的代码:
void iterater(Public_Airplane* p_a) {
cout << "Crew = " << p_a->Crew << endl;
cout << "SeatingCapacity = " << p_a->SeatingCapacity << endl;
...
}
一般模式是打印名称的字符串表示形式,然后是等号,然后使用箭头操作符从类中选择该成员。这里有一种方法:
void iterater(Public_Airplane *p_a)
{
#define X(type, name) cout << #name << " = " << p_a->name << endl;
X_AIRCRAFT
#undef X
}
使用字符串化操作符#将名称转换为自身的引号版本。
相关文章:
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 包含 std::list 的结构体的 C++ 初始化
- 结构体和类的不同大小(),彼此具有相同的字段类型
- 如何使用结构体的向量数组?
- 如何使用结构体在C++中更改这些代码?
- 无法在 Mosquitto MQTT Broker 插件上访问结构体 mosquitto 的元素
- 我应该如何在C++中使用结构体解决输入失败的问题?
- Qsort() 比较结构体整数的总和
- 如何使用迭代器指向结构体c++的向量
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 如何获取结构体成员的地址
- 创建结构体向量,表达式:向量下标超出范围
- boost::任何带有结构体和无符号整数
- 如何在构造函数中初始化结构体的动态数组?
- 只写结构体的某些字段
- C++ push_back() 一个结构体到一个向量中
- C++14 结构体上的统一初始化
- 如何从类库返回一个结构体数组到控制台应用程序