gpt4 book ai didi

c++ - ostringstream 用 void * 重载 const char *

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

我对 ostream 有疑问,我已经编写了一个非常基本的宏,应该打印出它的参数。

请看下面的示例代码:

#define LOG Message(__FILE__, __LINE__,__func__)

class Message : public std::ostringstream
{
public:
Message(const char *param1, int param2, const char *param3)
{
*this<<param3<<"("<<param1<<":"<<param2<<")";
}
~Message()
{
*this<<endl;
cout<< rdbuf()->str();
}
};


int main()
{
int integer = 1;
string str = "XYZ";

LOG<<integer<<"DEBUGLOG1: "<<str<<" "<<integer;
return 0;
}

问题是如果我使用:

LOG << "LOG1: " << str << " " << integer;

输出打印 Address* const char* "LOG1: "而不是值。

但是,如果我使用:

LOG << integer << "DEBUGLOG1: " << str << " " << integer;

输出完美,打印整数值和字符值。

它看起来像而不是使用 ostream& operator<< (ostream& out, const char* s );

它正在使用 ostream& operator<< (const void* val);

谁能阐明可以做些什么来克服这种重载?

提前致谢

最佳答案

问题是 Message(...)是临时的。临时无法绑定(bind)到 operator<< 的非常量引用参数.

它只能与成员函数和运算符一起使用,如ostream::operator<<(int) .

奇怪的是,成员运算符返回一个引用,而该引用又可以与非成员运算符一起使用。

关于c++ - ostringstream 用 void * 重载 const char *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10739798/

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