上课的自定义操纵器 [英] Custom manipulator for class

查看:83
本文介绍了上课的自定义操纵器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写带有参数的流操纵器. 我的班级是3 int的CDate(年,月,日). 因此,我需要制作操纵器date_format(const char*). 例如:

I'm trying to write a stream manipulator with arguments. I have class with 3 int's CDate(Year, Month, Day). So I need to make manipulator date_format(const char*). e.g. :

CDate a(2006, 5, 15);
cout <<"DATE IS : " << date_format("%Y-hello-%d-world-%m-something-%d%d") << a;

输出将是:

DATE IS : 2006-hello-15-world-5-something-1515

猜猜我需要使用

ios_base & dummy_date_format_manipulator ( ios_base & x )
{
    return x;
}

ios_base & ( * ( date_format ( const char * fmt ) ) )( ios_base & x )
{
    return dummy_date_format_manipulator;
}

但是我不知道怎么做.

推荐答案

您可以为此使用pword数组. C ++中的每个iostream都有两个与之关联的数组.

You can use pword array for this. Every iostream in C++ has two arrays associated with it.

ios_base::iword - array of ints
ios_base::pword - array of void* pointers

您可以在其中存储自己的数据.若要获取索引,该索引引用所有iwordpword数组中的空元素,则应使用函数std::ios_base::xalloc().它返回int,您可以将其用作*word中的唯一索引. 您应该在启动时获取一次该索引,然后将其用于*word的所有操作.

You can store you own data in it. To obtain an index, that refers to an empty element in all iword and pword arrays you should use function std::ios_base::xalloc(). It returns int that you can use as an unique index in *word. You should obtain that index once on the start-up, and than use it for all operations with *word.

然后编程您自己的操作将如下所示:

Then programming your own manip will look like:

操纵器函数接收对ios_base对象的引用和对格式字符串的指针,只需将该指针存储在pword

Manipulator function, that receives reference to ios_base object and pointer to the format string, simply stores that pointer in pword

iosObject.pword(index_from_xalloc) = formatString

然后,重载的运算符<<(>>)以相同的方式从iostream对象获取格式字符串.之后,您只需参考格式进行转换即可.

Then overloaded operator << (>>) obtains format string from the iostream object in the same way. After that you just make a conversion referencing to the format.

这篇关于上课的自定义操纵器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆