gpt4 book ai didi

C++ OStream 继承和操纵器

转载 作者:太空宇宙 更新时间:2023-11-04 12:17:11 25 4
gpt4 key购买 nike

我有一个继承自 ostream 的类但操纵器无法编译。例如:

QLogger &logger = QLogger::getInstance();

logger << hex << 10 << endl;

投诉logger << hex .如果我将记录器转换为 ostream它会起作用,但那是相当笨手笨脚的。

如何扩展我的类,使其表现得像一个 ostream与操纵器?

谢谢,

肯尼

class LIBEXPORT QLogger: public std::ostream
{
friend class boost::thread_specific_ptr< QLogger >;

friend class QLoggerFunnel;

public:

// Priority for message filtering.
//
// DEBUG Detailed information that may be useful during development or troubleshooting.
// NORMAL Message will be useful during normal operation.
// WARNING Message indicates an unhealthy condition but the system should continue to operate.
// FAULT Message indicates a critical error. The system may not operate normally.
enum Priority
{
DEBUG, NORMAL, WARNING, FAULT
};

// DEPRECATED: Defined for backward compatibility.
static const Priority LOW = NORMAL;

static const Priority HIGH = WARNING;

static const Priority URGENT = FAULT;

// Returns a reference to the global instance.
static QLogger& getInstance();

// DEPRECATED: Use instead: QLogger::instance() << "Example message." << std::endl
static AWI_DEPRECATED QLogger& stream( QLogger::Priority priority = NORMAL );

QLogger &operator<<( Priority p );

// Messages with a priority below the threshold are discarded.
void setThreshold( Priority priority );

Priority getThreshold( void ) const;

// Set the priority of messages.
void setPriority( Priority priority );

Priority getPriority( void ) const;

protected:

static void handleThreadExit( QLogger *logger );

QLogger();

QLogger( const QLogger& );

virtual ~QLogger();

QLogger& operator=( const QLogger& );

void write( std::ostream &destination );

void synchronize( void );

// Prepends information to each line of its associated output stream.
class StampBuffer: public std::stringbuf
{
public:

StampBuffer();

virtual ~StampBuffer();

// String to be displayed before each line.
void setPreamble( const char *p );

virtual int sync();

void write( std::ostream &destination );

protected:

boost::mutex _mutex;

std::stringstream _stream1;

std::stringstream _stream2;

// Active stream being written to.
std::stringstream *_write;

std::stringstream *_read;

const char *_preamble;
};

class NullBuffer: public std::stringbuf
{
public:

NullBuffer();

virtual ~NullBuffer();

virtual int overflow( int c )
{
return (c);
}
};

StampBuffer _buffer;

NullBuffer _null_buffer;

Priority _threshold;

Priority _priority;
};

最佳答案

如果您实现了一个成员函数,那么在重载决策中将不会考虑继承该相同函数的重载。如果您更改自定义 operator<<重载成为 friend 全局函数而不是成员,这应该可以正常工作。强制转换强制编译选择 operator<<()来自 ostream 中定义的那些.

不需要函数指针的特殊重载。

关于C++ OStream 继承和操纵器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7152096/

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