C++ 运算符重载 (v << 1,2,3;)?

c++ operator overloading (v << 1,2,3;)?

本文关键字:lt 运算符 C++ 重载      更新时间:2023-10-16

看看下面的语法:

Matrix<int , 3 , 3 > m;
m << 1, 2, 3,
     4, 5, 6,
     7, 8, 9;
std::cout << m;
输出:

1 2 3
4 5 6
7 8 9

如何重载第一个<<

以下内容可能对您有所帮助:https://ideone.com/Ap6WWt

template <typename T, int W, int H>
class MatrixStream
{
public:
    MatrixStream(Matrix<T, W, H>& mat, const T& value) : mat(mat), index(0)
    {
        *this, value;
    }
    MatrixStream& operator , (const T& value);
private:
    Matrix<T, W, H>& mat;
    int index;
};
template <typename T, int W, int H>
class Matrix
{
public:
    MatrixStream<T, W, H> operator << (const T& value) {
        return MatrixStream<T, W, H>(*this, value);
    }
    T m[W][H];
};
template <typename T, int W, int H>
MatrixStream<T, W, H>& MatrixStream<T, W, H>::operator , (const T& value)
{
    assert(index < W * H);
    int w = index / H;
    int h = index % H;
    mat.m[w][h] = value;
    ++index;
    return *this;
}

但是重载operator ,是非常不鼓励的。正如评论中所说,您可以使用替代m << {1, 2, 3, 4, 5, 6, 7, 8, 9}m << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9

当您使用如下表达式时:

CleanInitArray a(6);
a = 1,2,3,4,5,6; 

由编译器这样读取:

((((((a=1),2),3),4),5),6);

因此,您需要重载赋值操作符以返回一个类数组对象,并使用该操作符重载逗号操作符。

在我的整个c++生涯中,我所见过的重载operator,的唯一有用的应用是Boost。赋值,甚至这在c++ 11中也变得多余了,多亏了std::initializer_list

尽管如此,知道它是如何工作的也无妨,所以我建议您只查看Boost源代码。它是开源的,您可以免费下载,并且它可以按预期工作。