代码之家  ›  专栏  ›  技术社区  ›  HexBlit

二进制“*”:找不到采用“统计学家”类型的全局运算符(或没有可接受的转换)

  •  2
  • HexBlit  · 技术社区  · 14 年前

    但是,当我重载(*)乘法运算符时,会出现以下错误:

         binary '*' : no global operator found which takes type 'statistician' 
    (or there is no acceptable conversion)
    

    当我的代码尝试执行以下操作时会发生这种情况: s = 2*u; 在主.cpp

    其中s和u是统计学家类。

    统计学家=我的班级

    (统计学家h)

    class statistician  
    {
    ... other functions & variables...
    
    const statistician statistician::operator*(const statistician &other) const;
    
    ..... more overloads...
    
    };
    

    任何帮助都会很棒的谢谢!!

    2 回复  |  直到 14 年前
        1
  •  5
  •   Johannes Schaub - litb    14 年前

    声明命名空间作用域 operator* 敞篷车 上的操作数 左边 不属于类型的手侧 statistician

    statistician operator*(const statistician &left, const statistician &right) {
      // ...
    }
    

    不用说,您应该删除类1中的,然后您需要一个转换构造函数来获取 int

        2
  •  4
  •   Dima    14 年前

    这就是为什么像*或+这样的二进制运算符应该是非成员的。

    如果你这么做了 s = u * 2 ,如果您有一个非显式构造函数 statistician 这需要一个 int 争论。然而, 2 * u 统计学家 内景 不是具有成员的类 operator* .

    操作员* 让它成为一个 friend 统计学家

    
    statistician operator*(const statistician &left, const statistician &right);
    

    您还需要定义 操作员* 接受整数(或任何其他类型的你希望能够“乘”)或定义非显式构造函数 启用隐式转换。