c++运算符重载看不到其他运算符

标签 c++ operator-overloading constants

我有一个问题。我已将自定义 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: no operator "*" matches these operandsnoperand types are: const Matrix * int

我该如何解决?

最佳答案

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

Matrix operator*(int arg) const;

关于c++运算符重载看不到其他运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20446926/

相关文章:

c++ - 从函数返回一个动态创建的数组

c++ - std::array 的重载 () 运算符给出:错误 C2039: '()':不是 'std::array<_Ty,_Size>' 的成员

c++ - 如何正确重载从基类到继承的转换

c++ - 将具有非 const 元素的 shared_ptr vector 转换为具有 const 元素的 shared_ptr vector

c++ - 通过在 C++ 中使用连接调用它来编辑字符串

C++:合并排序和插入排序混合

c - 我无法确定为什么这个 C 程序会给我这个答案

基于 Rails 变量的 Javascript 条件

c++ - 将临时变量写入 Json : I get\u0000

c++ - Ubuntu 中的 "int"