dar*_*rko 0 c++ operator-overloading
我正在进行一项任务,向我介绍运算符重载.我必须将一些二元运算符作为成员函数和朋友函数重载.我的成员函数重载"+"运算符工作正常但我的朋友函数重载" - "运算符似乎很难找到成员函数能够使用的数据.
class def:
class matrix
{
friend ostream& operator << (ostream&, const matrix&);
friend bool operator == (const matrix &, const matrix &);
friend matrix operator - (const matrix &, const matrix &);
private:
int size;
int range;
int array[10][10];
public:
matrix(int);
matrix(int, int);
bool operator != (const matrix &) const;
matrix operator + (const matrix &) const;
const matrix & operator = (const matrix &);
};
Run Code Online (Sandbox Code Playgroud)
"+"过载:
matrix matrix::operator + (const matrix & a) const
{
matrix temp(size,range);
for (int i = 0; i < a.size; i++)
for (int j = 0; j < a.size; j++)
temp.array[i][j] = a.array[i][j] + array[i][j];
return temp;
}
Run Code Online (Sandbox Code Playgroud)
" - "过载:
matrix operator - (const matrix & a, const matrix & b)
{
matrix temp(size, range);
for (int i = 0; i < a.size; i++)
for (int j = 0; j < a.size; j++)
temp.array[i][j] = a.array[i][j] - array[i][j];
return temp;
}
Run Code Online (Sandbox Code Playgroud)
我在友元函数中得到的错误是大小,范围和数组都是未声明的.我很困惑,因为我认为成员和朋友函数都可以同等地访问类中的数据,而且我在两个函数中基本上都做同样的事情.有谁知道我的问题可能是什么?
朋友运营商不属于班级.因此,它不知道size和range和array.你必须使用对象a和b.它应该是这样的:
matrix operator - (const matrix & a, const matrix & b)
{
if(a.size != b.size)
throw std::exception(...);
matrix temp(a.size, a.range);
for (int i = 0; i < a.size; i++)
for (int j = 0; j < a.size; j++)
temp.array[i][j] = a.array[i][j] - b.array[i][j];
return temp;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1407 次 |
| 最近记录: |