【问题标题】:Printing XMacro struct to the console with C++使用 C++ 将 XMacro 结构打印到控制台
【发布时间】:2016-10-19 23:44:00
【问题描述】:

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

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

这是我的 x 宏

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

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

【问题讨论】:

  • 重写cout &lt;&lt; "Value: = " name;cout &lt;&lt; "Value: = " &lt;&lt; name;,也许?
  • 我刚注意到错字。我将

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


【解决方案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
}

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

【讨论】:

  • 我正要试一试。感谢您的意见!
  • 你的代码更有意义,但是当我单步执行程序时,它通过函数而不执行代码。
  • 我不知道这是否重要,但是当我对文件进行预处理时,我看不到预处理器的代码。我以为我可以期待看到 int Crew;诠释座位容量; ... 等等。但该文件没有这些。为了使用 xmacros,我需要使用一些包含吗?
  • 这段代码在我的系统上运行良好——也许我们有不同的设置?我建议您使用当前版本的代码发布一个新问题,以便我们查看。
  • 我会这样做的。谢谢。
猜你喜欢
  • 2012-04-16
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
相关资源
最近更新 更多