user2701639
user2701639

Reputation: 921

what is it? C++ macro function? how to replace this macro? Could I have an example?

#define functionA()\
protected:\
static int a;\
int b;\
string c;

#define functionB()\
functionA()\
public:\
virtual int getvalue_a(){return a;}\
virtual void setvalue_b(int VB){b = VB; }\
virtual int get value_b(){return b;}

I want to convert this kind of code to regular code. I want to use class or regular function to replace the macro.

but I don't know what's the relationship of "functionA()" and "functionB()", Do they are inherentence? or "functionA()" is a private data of functionB()?

Thanks for your answer.

Upvotes: 0

Views: 117

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106166

Macros perform a substitution in the source code before the subsequent stages of C++ compilation kick in. Here, anywhere functionA() appears in the source, the text "protected: static int a; int b; string c;" will be substituted (assuming your slashes '/' are actually backslashed '\', which is the line-continuation character for multi-line macros). Note that the line continuation is replaced by single spaces - not that it tends to matter.

Wherever "functionB()" appears, its text will be substituted, with the "functionA()" substitution then further expanded within the substituted text.

Functionally, these macros happen to inject source code that includes protected: and public:, so they can only be valid inside a struct or class. The former adds a few data members to the class it appears in - the latter additionally contributes some public virtual member functions.

To convert the code to regular code, you can either perform the substitutions once by hand then save the resultant file, or perhaps ask the compiler to perform the substitutions for you... for example many compilers will output preprocessed (macro-expanded) code when given the "-E" or "/E" command line option. Unfortunately, that will affect all the other preprocessor changes too (include #includes of headers), so it may be considerable work to cut-and-paste only the substitutions you want.

For example:

class X
{
    ...whatever stuff...
    functionA()
    ...whatever stuff...
};

...can be replaced with...

class X
{
    ...whatever stuff...
  protected:
    static int a;
    int b;
    string c;
    ...whatever stuff...
};

While a use of functionB expands from something like...

struct Y
{
    ...whatever stuff...
    functionB()
    ...whatever stuff...
};

...to...

struct Y
{
    ...whatever stuff...
  protected:
    static int a;
    int b;
    string c;
  public:
    virtual int getvalue_a(){return a;}
    virtual void setvalue_b(int VB){b = VB; }
    virtual int get value_b(){return b;}
    ...whatever stuff...
};

Upvotes: 2

Related Questions