gpt4 book ai didi

c++ - 错误记录 C++ 预处理器宏 __LINE__、__FUNCTION__

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:09:07 24 4
gpt4 key购买 nike

我试图将一个简单的错误记录合并到我现有的应用程序中,目前它仅使用 cout 报告错误所以我希望使用 << 保持类似的界面运算符(operator)。但是我希望它记录该行并运行发生的错误,但我不想输入 __LINE__, __FUNCTION__每次我需要登录。有谁知道我可以用来允许 __LINE__ 的技巧吗?要在另一个函数中使用的宏,而不是报告调用行?希望这是有道理的。

class myLogClass {
uint8_t level;
public:
bool operator<<( const char * input );
};

bool myLogClass::operator<<( const char * input ) {
logItInSQL( input );
return true;
}

而不是每次都这样

myLogClass << "Line No: " << __LINE__
<< " Function: " << __FUNCTION__
<< " Error: " << "This is my error to be logged";

我只想能够做到:

myLogClass << "This is my error to be logged";

bool myLogClass::operator<<( const char * input ) {
logItInSQL( " Line No: __LINE__" );
logItInSQL( " Function: __FUNCTION__" );
logItInSQL( " Error: " + input );
return true;
}

最佳答案

myLogClass << "Line No: " << __LINE__ ...

用你的operator <<链接将不起作用,因为它返回 bool .

bool myLogClass::operator << (const char * input)

习惯上定义流插入如下:

std::ostream& myLogClass::operator << (std::ostream& o, const char * input) {
// do something
return o;
}

这样做:

#define log(o, s) o << "Line No: " << __LINE__ << \
" Function: " << __FUNCTION__ << \
" Error: " << s // note I leave ; out

此外,您可以将宏包装在 do-while 中循环:

#define log(o, s) do { o << "Line No: " << __LINE__ << \
" Function: " << __FUNCTION__ << \
" Error: " << s; \
} while(0) // here, I leave ; out

然后就可以愉快的写了:

 myLogClass myLogger; // do this

// use it
log(myLogger, "This is my error to be logged"); // note the ;

关于c++ - 错误记录 C++ 预处理器宏 __LINE__、__FUNCTION__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/622129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com