首页 > 解决方案 > 如何重载 << 运算符使其仅影响类的成员?

问题描述

我有一个Bitset存储 a vectorof chars 的类,并且我希望能够,每当我使用 时,仅当它是该类的一部分时cout << char才能将其转换为 short int。char

代码:

模板<long long X>
类位集
{
    公共:std::vector<unsigned char> 位 = std::vector<unsigned char> ((X+7)/8);

    上市:
        /* 构造函数 */

        朋友 std::ostream &operator<< (std::ostream &output, const char x);
};

std::ostream &operator<< (std::ostream &output, const char x)
{
    输出<<(短)(x);
    返回输出;
}

这个想法是,如果我写:

位组一个;
/* 代码 */
cout << a.bit[x];
cout << 'a';

我想投进a.bit[x]一个短片,但不是'a'那么好。

标签: c++classcastingcharoperator-overloading

解决方案


你不能超载operator<<char按照你想要的方式行事。它不知道char来自哪里,所以它不能根据来源表现不同。

为了使这项工作以您想要的方式进行,您必须Bitset自己实现operator[]返回代理对象,然后您可以operator<<为该代理重载,例如:

template<long long X>
class Bitset
{
private:
    std::vector<unsigned char> bits = std::vector<unsigned char> ((X+7)/8);

public:
    /* constructors */

    class BitProxy
    {
    private:
        unsigned char &bit;

    public:
        BitProxy(unsigned char &bit) : bit(bit) {}

        BitProxy& operator=(unsigned char x) { bit = x; return *this; }
        operator unsigned char() const { return bit; }
    };

    BitProxy operator[](size_t index) { return BitProxy(bits[index]); }

    friend std::ostream& operator<< (std::ostream &output, const BitProxy &x)
    {
        output << static_cast<short>(static_cast<unsigned char>(x));
        return output;
    }
};
Bitset a;
// populate a as needed...
cout << a[x];
cout << 'a';

现场演示


推荐阅读