如何重载 << 运算符使其仅影响类的成员?

H-0*_*005 1 c++ casting class operator-overloading char

我有一个Bitset存储 a vectorof chars的类,我希望能够在我使用cout << char时将它char转换为一个 short int ,前提是它是该类的一部分。

代码:

模板<长长X>
类位集
{
    公共:std::vector<unsigned char> bit = 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);
    返回输出;
}

这个想法是,如果我写:

位集 a;
/* 代码 */
cout << a.bit[x];
cout<<'a';

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

Rem*_*eau 5

你不能重载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;
    }
};
Run Code Online (Sandbox Code Playgroud)
Bitset a;
// populate a as needed...
cout << a[x];
cout << 'a';
Run Code Online (Sandbox Code Playgroud)

现场演示