【发布时间】:2011-11-10 18:55:13
【问题描述】:
我有一个 Linux 上的 C++ 类,它允许我在控制台上显示消息,具体取决于应用程序的运行位置。如果它在我的计算机上运行,则消息以控制台模式显示。否则,所有内容都会记录在文本文件中以供以后查看。我创建了一个外部对象来使用它。我想尝试使这个类成为单例,但没有成功。我有这个错误似乎是当我来编译我的程序时:
错误:'Log *'和'const char [12]'类型的无效操作数到二进制'operator
还有:
错误:'logOutput' 中的'operator
我想听听你的意见。提前感谢您的关注。
我目前的功能类
typedef std::vector<unsigned char> Buffer_T; class Log { public: Log(); virtual ~Log(); void init() { #indef FriendlyArm output = new ofstream("/home/arm/Log.txt"); #else output = &cout; #endif } template<typename T> Log operator<<( T const& value ) { (*output) << value; return *this; } Log& operator<<( std::ostream&(*f)(std::ostream&) ) { (*output) << f; return *this; } Log& operator<<(Buffer_T& Buf) { if( Buf.size() > 0 ) { for( unsigned int i = 0; i < Buf.size(); i++ ) { if( Buf[i] >= 32 && Buf[i] <= 127 ) { (*output) << Buf[i]; } else { (*output) << "0x" << std::setfill( '0' ) << std::hex << std::setw( 2 ) << unsigned( Buf[i] ); } } } return *this; } private: ostream *output; }; #endif /* LOG_H_ */这是我单身的尝试
typedef std::vector<unsigned char> Buffer_T; class Log { public: static Log *createOrGet() { if(_unique == NULL) { _unique = new Log(); } return _unique; } static void kill() { if(_unique != NULL) { delete _unique; _unique = NULL; } } void init() { #indef FriendlyArm output = new ofstream("/home/arm/Log.txt"); #else output = &cout; #endif } template<typename T> Log operator<<( T const& value ) { (*output) << value; return *this; } Log& operator<<( std::ostream&(*f)(std::ostream&) ) { (*output) << f; return *this; } Log& operator<<(Buffer_T& Buf) { if( Buf.size() > 0 ) { for( unsigned int i = 0; i < Buf.size(); i++ ) { if( Buf[i] >= 32 && Buf[i] <= 127 ) { (*output) << Buf[i]; } else { (*output) << "0x" << std::setfill( '0' ) << std::hex << std::setw( 2 ) << unsigned( Buf[i] ); } } } return *this; } private: Log(); virtual ~Log(); static Log *_unique; ostream *output; }; Log *Log::_unique = NULL; #endif
【问题讨论】:
-
@John 他们大多数时候并不理想,但总是让某人抱怨他们有多讨厌他们,这很烦人。你知道,单例可以很有用;只需检查一些 Boost 库的实现即可。
-
@Paul:我不是在和你说话。 OP 可能没有意识到单例通常是一种糟糕的设计技术。
-
@John 你不是在跟我说话吗?!你几岁?!
-
@Paul:我只是想指出我不是在“窃听”你。我在“窃听” OP。
-
@Jean:请发布复制此问题的测试代码。
标签: c++ linux pointers singleton operator-overloading