【发布时间】:2018-06-27 15:51:04
【问题描述】:
使用“=”为类成员设置一些值并提供附加参数的正确语法是什么?例如。向量中的位置:
MyClass<float> mt;
mt(2,4) = 3.5;
我试过了:
template <class _type>
_type myClass<_type>::operator()(int r,int c) {
return data[r*nCols+c];
};
template <class _type>
myClass<_type>::operator= (int r, int c, _type val) {
data(r,c) = val;
};
但是编译器告诉我我可以用 1 个参数覆盖 '=' 运算符。
【问题讨论】:
-
operator =应该将一个MyClass分配给另一个MyClass。如果您想分配给一个元素,请使用operator()访问该元素,就像使用mt(2,4) = 3.5;一样 -
@NathanOliver 它不起作用,我收到“错误:需要左值作为赋值的左操作数”
-
operator=可以采用的参数集非常有限。实际上只有一个参数,它是被复制的对象。推荐阅读:What are the basic rules and idioms for operator overloading?
标签: c++ class templates operators overriding