[英]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.