【问题标题】:How overload the '=' operator with arguments?如何用参数重载“=”运算符?
【发布时间】: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


【解决方案1】:

当您重载= 运算符时,您只希望在参数中有右手边的值。由于您重载了 () 运算符,因此您不需要使用 = 运算符处理 rc 值。您可以只使用mt(2,4) = 3.5;,重载的() 运算符将处理mt(2,4) 部分。然后,您可以将返回的数据设置为您想要的值,而无需重载任何 = 运算符。

您需要返回对数据的引用以便编辑它,但是:

template <class _type>
_type& myClass<_type>::operator()(int r,int c) {
    return data[r*nCols+c]; 
};

【讨论】:

  • 谢谢,我错过了参考位!
猜你喜欢
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多