【问题标题】:c++ Operator overloading not seeing other operatorsc ++运算符重载看不到其他运算符
【发布时间】:2013-12-07 21:31:49
【问题描述】:

我有问题。我已经实现了一个自定义的operator* 作为成员函数。

在标题中:

class Matrix
{
public:
Matrix operator*(int arg); //(1)
...
}

Matrix operator*(int a, const Matrix& m)
{
    return m * a; //(2)
}

(1) 我可以在 main.cpp 中做到这一点:

Matrix a = Matrix::GetRandom.....
Matrix b = a * 2;

(2) 在这一行,我得到一个编译器错误:

IntelliSense:没有操作符“*”匹配这些操作数noperand 类型是:const Matrix * int

我该如何解决?

【问题讨论】:

  • 您也可以将这两个运算符写为(非成员)朋友函数friend Matrix operator(Matrix, int);friend Matrix operator(int, Matrix);。这使两者保持对称,并且它们彼此相邻声明。

标签: c++ operator-overloading constants


【解决方案1】:

mconst,所以只能调用const 方法。将Matrix::operator* 设为const 成员函数:

Matrix operator*(int arg) const;

【讨论】:

    【解决方案2】:

    您的运算符重载声明中缺少const

    Matrix operator*(int arg) const;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-26
      • 2017-02-27
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多