繁体   English   中英

我的宏函数怎么了?

[英]What's wrong with my macro function?

我使用换行符“ \\”定义了多行宏函数,如下所示:

#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语句中的块之后形成一个空语句,而else将没有if匹配。

反斜杠必须是该行的最后一个字符,才能继续该行。

您的某些反斜杠后面有空格。

在Visual Studio编辑器中Ctrl+Shift+8 ,然后在尾随\\后面看到所有空格-删除它们!

暂无
暂无

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

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