用宏调用 class 函数

Call class function with macro

这里我想用宏 MPRINT() 从 class Hello 调用 world 函数,但它不识别宏语法:

#include <windows.h>
#include <iostream>
#include <string.h>

using namespace std;

// first try
#define MPRINT(text) \
    []() -> Hello::world(#text)\
    }()

// second try
#define MPRINT(text) \
Hello obj; \
obj.world(text);

class Hello
{
public:
    string world(string inp);
};

string Hello::world(string inp) {
    return inp + "|test";
}

int main()
{
    string test1 = MPRINT("blahblah"); // error "type name is not allowed"
    cout << MPRINT("blahblah"); // error "type name is not allowed"
    return 0;
}

您第一次尝试使用 Hello::world,但这不是调用非静态成员函数的正确语法。

在您的第二次尝试中,使用 MPRINT 将导致:

string test1 = Hello obj; obj.world(text); ;

这也显然是无效的。

你可以这样写宏:

#define MPRINT(text)            \
    [] {                        \
       Hello obj;               \
       return obj.world(#text); \
    }()

这是 demo

话虽如此,我强烈建议您不要为此类事情使用宏。以下函数运行良好:

auto MPRINT(std::string text) 
{                        
  Hello obj;               
  return obj.world(text); 
};

这里是 demo