所以我有以下代码:
#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);
,我该如何使用它?我从研究中知道,逗号运算符的重载是不寻常的,但是我需要这样做,因为这是项目要求中的问题。
最佳答案
How do I implement the comma operator so that
obj = 1, 2, 7
will do the exact same thing as doingobj.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 toobj.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/