【问题标题】:binary 'operator *' has too many parameters二进制 'operator *' 有太多参数
【发布时间】:2014-10-30 16:16:26
【问题描述】:

我正在制作一个带有模板的自定义矩阵类,用于教育目的。我要我的课 按以下方式工作:

mat*2; //Works
2*mat; //Should also work

对于第一种情况,我有以下声明

matrix<T> operator*(const T& a) const;

和实现

template <typename T>
matrix<T> matrix<T>::operator*(const T& a) const{
//Implementation here
}

而对于第二种情况,我必须将实现作为非成员类进行

matrix<T> operator*(T& a, matrix<T>& mat);

实现

template<typename T>
matrix<T> operator*(T& a, const matrix<T>& mat){
    return mat*a;
}

但是,当我尝试编译它时,我使用 MSVC 得到以下错误

error C2804: binary 'operator *' has too many parameters
..\main.cpp(33): error C2678: binary '*' : no operator found which takes a left hand operand of      type 'int' (or there is no acceptable conversion)

【问题讨论】:

  • 请添加更多上下文。我怀疑你在类定义中放置了matrix&lt;T&gt; operator*(T&amp; a, matrix&lt;T&gt;&amp; mat);
  • 试试在第二个函数的参数中加入const?它可能无法传递对文字 2 的非常量引用。
  • 这两件事我都做了,而且效果很好。你们能解释一下为什么会这样吗?我正在尝试在这里学习更多 C++。 :)

标签: c++ templates operator-overloading


【解决方案1】:

第一个参数类型必须是TT const &amp;

非 const lvalue 引用不能绑定到像 2 这样的文字(或临时对象或 const 对象或引用)。

【讨论】:

    【解决方案2】:

    根据我的评论:非静态类方法具有类类型的隐式第一个参数(*this)。如果放置在类定义中,您定义的运算符将具有三个参数(而二进制 operator* 应该只有 2 个)。如果将运算符声明放在类定义中,则需要删除第一个参数并直接使用类字段。

    【讨论】:

      猜你喜欢
      • 2016-06-26
      • 2013-03-24
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多