c++ - 如何用参数重载“=”运算符?
问题描述
使用“=”为类成员设置一些值并提供其他参数的正确语法是什么?例如向量中的位置:
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 个参数覆盖 '=' 运算符。
解决方案
当您重载=
运算符时,您只希望在参数中有右手值。由于您重载了()
运算符,因此您不需要使用运算符处理r
andc
值=
。您可以只使用mt(2,4) = 3.5;
,重载的()
运算符将处理该mt(2,4)
部分。然后,您可以将返回的数据设置为您想要的值,而无需重载任何=
运算符。
您需要返回对数据的引用,以便可以对其进行编辑,但是:
template <class _type>
_type& myClass<_type>::operator()(int r,int c) {
return data[r*nCols+c];
};
推荐阅读
- javascript - 有没有办法将私人频道添加到 twilio 可编程聊天中?
- c# - 为文件夹分支中的所有类启用 C# 8.0 的可空引用类型功能
- python - python pandas用iterrows迭代数据帧行很慢,可以以某种方式替换吗?
- java - 从 java 命令行应用程序中读取 cmd 的 cd
- javascript - JS:根据来自同一元素的不同属性值确定属性值(使用 .push 方法)
- reactjs - react-router中'/'和'/anything'的重定向有什么区别?
- ruby-on-rails - 使用 Apple 登录:在服务器端验证令牌
- python - 在继续执行程序之前,如何确保对另一个程序的调用已完成?
- html - 圆形跨度标签的响应度
- sql - 向下填充顶层详细信息