我使用续行符“\”定义了一个多行宏函数,如下所示:
#define SHOWMSG( msg ) \
{ \
std::ostringstream os; \
os << msg; \
throw CMyException( os.str(), __LINE__, __FILE__ ); \
}
但它无法通过编译。顺便说一句,我正在使用 VS2008 编译器。请问我上面的宏函数有什么问题吗?
最佳答案
多语句宏的常用方法是这样的:
#define SHOWMSG(msg) \
do { \
std::ostringstream os; \
os << msg; \
throw CMyException(os.str(), __LINE__, __FILE__); \
} while (0)
否则,右大括号后的分号会导致句法问题,例如:
if (x)
SHOWMSG("This is a message");
else
// whatever
按原样使用您的代码,这将扩展为:
if (x) {
std::ostringstream os;
os << "This is a message";
throw CMyException(os.str(), __LINE__, __FILE__);
}
; // on separate line to emphasize that this is separate statement following
// the block for the if statement.
else
// whatever
在这种情况下,分号将在 if
语句 block 之后形成一个空语句,而 else
不会有 if
匹配。
关于c++ - 我的宏函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6853751/