64,637
社区成员
发帖
与我相关
我的任务
分享
template<class T>
log& operator<<(const T& anyMessage)
{
m_logFile << anyMessage;
return *this;
}
[/quote]
不返回自己怎么接着玩下去呢?
例如这里一步步来是这样的:
log("log.txt") << "hello, this is a number: " << 1234 << " and a string: " << aStr << std::endl;
log("log.txt") 构造了一个匿名对象假设叫做 mylog 吧
第一步执行:
mylog << "hello, this is a number: "
然后返回了自己就是 mylog
然后再来
mylog << 1234
然后又返回了自己就是 mylog
然后再来
mylog << " and a string: "
[/quote]
直接说为了实现链式表达式不就行了吗?这么纠结。。。[/quote]
为了尽量说得简单点template<class T>
log& operator<<(const T& anyMessage)
{
m_logFile << anyMessage;
return *this;
}
[/quote]
不返回自己怎么接着玩下去呢?
例如这里一步步来是这样的:
log("log.txt") << "hello, this is a number: " << 1234 << " and a string: " << aStr << std::endl;
log("log.txt") 构造了一个匿名对象假设叫做 mylog 吧
第一步执行:
mylog << "hello, this is a number: "
然后返回了自己就是 mylog
然后再来
mylog << 1234
然后又返回了自己就是 mylog
然后再来
mylog << " and a string: "
[/quote]
直接说为了实现链式表达式不就行了吗?这么纠结。。。template<class T>
log& operator<<(const T& anyMessage)
{
m_logFile << anyMessage;
return *this;
}
[/quote]
不返回自己怎么接着玩下去呢?
例如这里一步步来是这样的:
log("log.txt") << "hello, this is a number: " << 1234 << " and a string: " << aStr << std::endl;
log("log.txt") 构造了一个匿名对象假设叫做 mylog 吧
第一步执行:
mylog << "hello, this is a number: "
然后返回了自己就是 mylog
然后再来
mylog << 1234
然后又返回了自己就是 mylog
然后再来
mylog << " and a string: "
template<class T>
log& operator<<(const T& anyMessage)
{
m_logFile << anyMessage;
return *this;
}
#include <iostream>
#include <fstream>
#include <string>
namespace Demo
{
class log
{
public:
log(const char* pszFileName)
{
m_logFile.open(pszFileName);
}
~log()
{
if (m_logFile.is_open())
{
m_logFile.close();
}
}
template<class T>
log& operator<<(const T& anyMessage)
{
m_logFile << anyMessage;
return *this;
}
typedef std::ostream& TFUNC(std::ostream&);
log& operator<<(TFUNC* pFunc)
{
pFunc(m_logFile);
return *this;
}
private:
std::ofstream m_logFile;
};
void Test()
{
std::string aStr("A_STRING");
log("log.txt") << "hello, this is a number: " << 1234 << " and a string: " << aStr << std::endl;
}
}
int main(int argc, char* argv[])
{
Demo::Test();
return 0;
}