c++ - 如何重载逗号运算符以将值分配给数组

标签 c++ operator-overloading comma-operator

所以我有以下代码:

#include <map>
#include <iostream>
using namespace std;

template<class V, unsigned D>
class SparseArray
{
public:

    map<string,V> data;

    SparseArray(){}

    class Index
    {
    private:
        int dims[D]{};
    public:
        int& operator[](int index)
        {
            return dims[index];
        }

        const int& operator[](int index) const
        {
            return dims[index];
        }

        friend ostream& operator<<(ostream& os, const SparseArray<V,D>::Index& index)
        {
            os << '{';
            for(int i=0;i<D;i++)
            {
                os<<index.dims[i];
                if(i+1!=D)os<<',';
            }
            os << '}';
            return os;
        }
        Index operator,(Index index)
        {

        }

        Index(){for(int i=0;i<D;i++){dims[i]=0;}}
    };

};

int main()
{
SparseArray<int,3>::Index i;

i[0] = 1;
i[1] = 2;
i[2] = 7;

//i = 1,2,7; - that's what i'm trying to make work

cout<<i;
}

如何实现逗号运算符,以便i=1,2,7i[0] = 1; i[1] = 2; i[2] = 7;完全相同
到目前为止,我所知道的是i=1,2,7等于i.operator=(1).operator,(2).operator,(7);,我该如何使用它?
我从研究中知道,逗号运算符的重载是不寻常的,但是我需要这样做,因为这是项目要求中的问题。

最佳答案

How do I implement the comma operator so that obj = 1, 2, 7 will do the exact same thing as doing obj.arr[0] = 1; obj.arr[1] = 2; obj.arr[2] = 7;?



这将完全改变comma operator的含义。我更喜欢初始化列表:
obj = {1, 2, 7};

在这种情况下使用逗号运算符。

I know from research that overloading comma operator is unusual, yet I need to do it as it's in the requirements of the project.



是的,我见过这样的老师。我认为他们只是想测试您是否可以在这些奇怪的约束下破解他们的任务。我的解决方案基于您问题本身的隐藏线索。

What I know so far is that obj = 1, 2, 7 is equivalent to obj.operator=(1).operator,(2).operator,(7);



究竟。请注意,此任务中operator,operator=几乎是同义的:
obj.operator=(1).operator=(2).operator=(7);

因此,这只是实现此技巧的问题:
Sample& Sample::operator,(const int& val)
{
    // simply reuse the assignment operator
    *this = val;

    // associativity of comma operator will take care of the rest
    return *this;
}

实现operator=取决于您。

那你可以做
obj = 1, 2, 7;

我编写了一个类似于您的示例的小型工作代码:Live Demo

编辑:

根据Jarod的建议(建议对这些运算符进行更合理的重载),可以按这种方式重载operator=(clear + push_back):
Sample& Sample::operator=(const int& val)
{
    arr[0] = val;
    length = 1;
    return *this;
}

并以这种方式operator,(push_back):
Sample& Sample::operator,(const int& val)
{
    // append the value to arr
    arr[length] = val;
    ++length;

    // associativity of comma operator will take care of the rest
    return *this;
}

将此想法放在一起:Demo 2

关于c++ - 如何重载逗号运算符以将值分配给数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61987787/

相关文章:

c++ - 如何将 Varaidic 模板化为模板中的返回类型?

c# - 在 C# 中设置 int 时,逗号运算符/分隔符的机制是什么?

c++ - 逗号运算符如何工作

c++ - Visual Studio 对话框编辑器不使用方形尺寸

带指针的 C++ 模板 - 无法转换模板参数

c++ - map/unordered_map 插入期间内存分配失败

c++ - 访问类/结构范围之外的 protected 成员?

C++ 错误 : passing const as 'this' argument

c++ - 如何使用重载运算符 [] 为左侧赋值?

javascript - 逗号运算符在参数列表中返回第一个值而不是第二个值?