C++ 参考手册

位置:首页 > C++ 参考手册 >输入/输出库 >std::ios_base > std::ios_base::iword

long& iword( int index );

首先,充分地分配或重置私有存储( long 的动态数组或另一可索引数据结构)以确保 index 是合法下标,然后返回到带下标 index 的私有存储 long 元素。

引用可能被此 ios_base 对象上任何其他操作非法化,包含另一对 iword() 的调用,但维持返回值,使得以相同下标从 iword(index) 读取将产生相同值(直至下次到 copyfmt() 的调用)。值能用于任何目的。必须通过先前的 xalloc() 调用获得元素下标,否则行为未定义。新元素初始化为 0

若分配失败,则调用可能抛出 std::ios_base::failurestd::basic_ios<>::setstate(badbit)

参数

index - 元素的下标值

返回值

到该元素的引用。

异常

设置 badbit 时可能抛出 std::ios_base::failure

示例

#include <iostream>
#include <string>
 
struct Foo {
    static int foo_xalloc;
    std::string data; 
    Foo(const std::string& s) : data(s) {}
};
 
// 分配 Foo 对象所用的 iword 存储
int Foo::foo_xalloc = std::ios_base::xalloc();
 
// 若 iword 保有 1 则此用户定义 operator<< 打印字符串
std::ostream& operator<<(std::ostream& os, Foo& f)
{
    if(os.iword(Foo::foo_xalloc) == 1)
        return os << std::string(f.data.rbegin(), f.data.rend());
    else
        return os << f.data;
}
 
// 此 I/O 操纵符在 0 与 1 间翻转存储于 iword 的数
std::ios_base& rev(std::ios_base& os)
{
    os.iword(Foo::foo_xalloc) = !os.iword(Foo::foo_xalloc);
    return os;
}
 
int main()
{
    Foo f("example");
    std::cout << f << '\n' << rev << f << '\n' << rev << f << '\n';
}

输出:

example
elpmaxe
example

参阅

若需要则重置私有存储的大小,并访问位于指定下标的 void* 元素
(公开成员函数)
[静态]
返回能安全用作 pword() 和 iword() 下标的程序范围内独有的整数
(公开静态成员函数)