c ++中的多行宏

问题描述 投票:-2回答:1

我试着为下面的代码编写宏,但测试用红色下划线,我不知道我声明的宏是否正确。代码是:

ABC Test{
int x,y,z;
AAA:
Test() : INIT(x),INIT(y),INIT(z) { }
CREATE(x);
CREATE(y);
CREATE(z);
};

我这个ABC字应该是“class”的等价物而AAA是“公共的”。我写的宏是:

#define ABC class name\
int _DATE_
#define AAA public
#define INIT(number)\
{int number = _COUNTER_}
#define ZERO  0
#define CREATE(number) number = ZERO;
c++ oop visual-c++ macros
1个回答
1
投票

如果m.cc是

#define ABC class name\
int _DATE_
#define AAA public
#define INIT(number)\
{int number = _COUNTER_}
#define ZERO  0
#define CREATE(number) number = ZERO;

ABC Test{
int x,y,z;
AAA:
Test() : INIT(x),INIT(y),INIT(z) { }
CREATE(x);
CREATE(y);
CREATE(z);
};

然后(当然也可以使用gcc):

pi@raspberrypi:/tmp $ g++ -E m.cc
# 1 "m.cc"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "m.cc"
# 9 "m.cc"
class nameint _DATE_ Test{
int x,y,z;
public:
Test() : {int x = _COUNTER_},{int y = _COUNTER_},{int z = _COUNTER_} { }
x = 0;;
y = 0;;
z = 0;;
};

所以缩进:

class nameint _DATE_ Test{
    int x,y,z;
  public:
    Test() : {int x = _COUNTER_},{int y = _COUNTER_},{int z = _COUNTER_} { }
    x = 0;;
    y = 0;;
    z = 0;;
 };

可能不是预期的结果;-)


也许你想要的东西:

#define ABC(name) class name {int _DATE_;
#define AAA public
#define INIT(number)  number(_COUNTER_)
#define ZERO  0
#define CREATE(number) int number = ZERO;

ABC (Test)
CREATE(x)
CREATE(y)
CREATE(z)
AAA:
Test(int _COUNTER_) : INIT(x),INIT(y),INIT(z) { }
};

然后 :

pi@raspberrypi:/tmp $ g++ -E  m.cc
# 1 "m.cc"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "m.cc"

class Test {int _DATE_;
int x = 0;
int y = 0;
int z = 0;
public:
Test(int _COUNTER_) : x(_COUNTER_),y(_COUNTER_),z(_COUNTER_) { }
};

所以缩进:

class Test {
    int _DATE_;
    int x = 0;
    int y = 0;
    int z = 0;
  public:
    Test(int _COUNTER_) : x(_COUNTER_),y(_COUNTER_),z(_COUNTER_) { }
};
© www.soinside.com 2019 - 2024. All rights reserved.