使用C ++将XMacro结构打印到控制台

时间:2016-10-19 23:44:00

标签: c++ macros c-preprocessor cout x-macros

我正在玩结构和类,我看到了一个非常酷的编码我想尝试:x-macro。

我的代码分为3位,标题,x-macro和主cpp文件。该程序尚未完成,仍然有代码覆盖和抛光,但我正在尝试使用x-macro构建一个结构,然后我想将结构的内容打印到屏幕上。

这是我的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类。然后我构建了三个继承了属性的子类。飞机并做了他们自己的东西。所以我会避免发布课程,除非你们认为我的问题就在那里。我要做的就是发布不能正常工作的功能......)

#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).

我做错了什么让我无法获得上面的代码输出?

1 个答案:

答案 0 :(得分:1)

您最终希望生成如下代码:

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
}

这使用字符串化运算符#将名称转换为自身的引用版本。