繁体   English   中英

用宏调用 class function

[英]Call class function with macro

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

#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 ,但这不是调用非静态成员 function 的正确语法。

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

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

这显然也是无效的。

你可以这样写宏:

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

这是一个演示

话虽如此,我强烈建议您不要将宏用于此类事情。 以下 function 运行良好:

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

这是一个演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM