C++ 函数的重载流运算符
我很好奇是否可以重载一个C++ 函数的重载流运算符,c++,C++,我很好奇是否可以重载一个你不能以你想要的方式提供重载 如果您必须使用的方法(OutputDebugString)强制您提供std::string(或类似)参数,那么您必须以某种方式提供该参数。一种方法是使用一个std::stringstream,将结果流到其中,然后将结果传递到OutputDebugString: std::stringstream ss; ss << whatever << " you " << want << to <&l
你不能以你想要的方式提供重载
如果您必须使用的方法(OutputDebugString
)强制您提供std::string
(或类似)参数,那么您必须以某种方式提供该参数。一种方法是使用一个std::stringstream
,将结果流到其中,然后将结果传递到OutputDebugString
:
std::stringstream ss;
ss << whatever << " you " << want << to << stream;
OutputDebugString(ss.str());
std::stringstream-ss;
ss使用此语法时,可以从具有运算符的函数返回对象。函数返回对象,而运算符MyLogFunction()
可以返回std::ostream&
。小心流对象的范围。我很困惑。std::ostream将如何向OutputDebugString@ScottF创建您自己的流对象,将其重定向到您想要的任何位置。
std::stringstream ss;
ss << whatever << " you " << want << to << stream;
OutputDebugString(ss.str());
#define OUTPUT_DEBUG_STRING(streamdata) \
do { \
std::stringstream ss; \
ss << streamdata; \
} while (0)
OUTPUT_DEBUG_STRING(whatever << " you " << want << to << stream);
#include <iostream>
#include <sstream>
class Logger {
std::stringstream ss;
public:
~Logger() {
// You want: OutputDebugString(ss.str());
std::cout<< ss.str();
}
// General for all types supported by stringstream
template<typename T>
Logger& operator<<(const T& arg) {
ss << arg;
return *this;
}
// You can override for specific types
Logger& operator<<(bool b) {
ss << (b? "Yep" : "Nope");
return *this;
}
};
int main() {
Logger() << "Is the answer " << 42 << "? " << true;
}