【问题标题】:How to overload the << operator so it only affects a member of a class?如何重载 << 运算符使其仅影响类的成员?
【发布时间】:2020-06-23 21:38:16
【问题描述】:

我有一个类 Bitset 存储一个 vector 的字符,并且我希望能够,每当我使用 cout &lt;&lt; char 时,将 char 转换为一个短整数,前提是它是其中的一部分类。

代码:

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

    上市:
        /* 构造函数 */

        朋友 std::ostream &operator

这个想法是,如果我写:

Bitset a;
/* 代码 */
cout 

我想将a.bit[x] 转换为短片,但也不想'a'

【问题讨论】:

  • 有点不清楚你在问什么。当您说“我希望能够,每当我使用 coutcout << a.bit[x]; 总是打印一个数字而不是一个ASCII 字符?这将需要char 以外的其他内容,但您可以使用一个包含字符的简单结构来完成。您也可以使用std::byte 更清楚地证明这不是一个字符

标签: c++ class casting char operator-overloading


【解决方案1】:

您不能重载 operator&lt;&lt; 以使 char 以您想要的方式运行。它不知道char 来自哪里,因此它的行为不会因来源而异。

要按照您想要的方式进行这项工作,您必须让Bitset 实现它自己的operator[],该operator[] 返回一个代理对象,然后您可以为该代理重载operator&lt;&lt; ,例如:

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';

Live Demo

【讨论】:

    【解决方案2】:

    我会采用一种非常简单的方法:只需在您的类中实现一个具有以下签名的函数:

    short GetElementAsShort (size_t index);
    

    然后你当然可以这样做:

    Bitset <128> a;
    std::cout << a.GetElementAsShort (42) << "\n";
    

    我真的不明白为什么需要更复杂的东西。当您阅读代码时,它还可以让您一目了然。

    【讨论】:

    • 嗯,是的,这是一种简单的方法,只是我在为自己设置挑战以进行练习。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多