[英]How to overload a comma operator to assign values to an array
所以我有以下代码:
#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[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.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;
}
把这个想法放在一起: Demo 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.