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

How to overload a comma operator to assign values to an array

本文关键字:分配 数组 运算符 何重载 重载      更新时间:2023-10-16

所以我有以下代码:

#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,7执行与执行i[0] = 1; i[1] = 2; i[2] = 7;完全相同的操作 到目前为止,我所知道的是i=1,2,7相当于i.operator=(1).operator,(2).operator,(7);,我该如何使用它? 我从研究中知道重载逗号运算符是不寻常的,但我需要这样做,因为它符合项目的要求。

如何实现逗号运算符,以便obj = 1, 2, 7将执行 和做obj.arr[0] = 1; obj.arr[1] = 2; obj.arr[2] = 7;完全一样的事情?

这将完全改变逗号运算符的含义。我更喜欢初始值设定项列表:

obj = {1, 2, 7};

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

我从研究中知道重载逗号运算符是不寻常的,但我 需要按照项目的要求进行操作。

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

到目前为止,我所知道的是,obj = 1, 2, 7相当于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;
}

把这个想法放在一起:演示 2