我想为我的矩阵类重载运算符+和=.我的代码是:
friend float* operator+(const Matrix& m)
{
for(int i = 0; i < (int)(m._n*m._n); i++)
_m[i] = _m[i] + m._m[i];
};
friend Matrix& operator=(const Matrix& m)
{
std::swap(_m, m._m);
return *this;
};
Run Code Online (Sandbox Code Playgroud)
与_m
数据和_n
方阵的大小.但是我的编译器给了我以下错误:
main.cpp:161:45: error: ‘Matrix& operator=(const Matrix&)’ must be a nonstatic member function
main.cpp: In function ‘float* operator+(const Matrix&)’:
main.cpp:192:12: error: invalid use of non-static data member ‘Matrix::_m’
main.cpp:158:13: error: from this location
main.cpp:192:12: error: invalid use of non-static data member ‘Matrix::_m’
main.cpp:158:21: error: from this location
main.cpp:159:5: warning: no return statement in function returning non-void [-Wreturn-type]
Run Code Online (Sandbox Code Playgroud)
对于第一个错误,我已经读过它必须直接在类中,但即使我把它放在那里,我仍然得到错误.对于第二个错误,我不知道如何解决这个问题.我究竟做错了什么?
谢谢!
如果您在类中定义某些内容friend
,则它不是成员函数,但为了方便起见,可以在类中定义一个独立的函数(字面上).
所以operator=()
当然不应该friend
只是一个简单的成员const Matrix& operator=(Matrix m)
或const Matrix& operator=(const Matrix& m)
.顺便说一下,std::swap()
如果您的参数是,则无法使用const Matrix& m
.你必须遵循复制和交换习惯用法.
对于operator+()
你应该选择:
friend Matrix operator+(const Matrix& m1, const Matrix& m2)
Matrix operator+(const Matrix& m1) const
. 归档时间: |
|
查看次数: |
272 次 |
最近记录: |