【发布时间】:2011-08-25 13:13:55
【问题描述】:
我正在处理一项向我介绍运算符重载的任务。我必须重载一些二元运算符作为成员函数和友元函数。我的重载“+”运算符的成员函数工作正常,但重载“-”运算符的朋友函数似乎很难找到成员函数能够使用的数据。
类定义:
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 &);
};
“+”重载:
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;
}
“-”过载:
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;
}
我在朋友函数中遇到的错误是大小、范围和数组都未声明。我很困惑,因为我认为成员函数和朋友函数都可以平等地访问类中的数据,而且我基本上在这两个函数中做同样的事情。有谁知道我的问题可能是什么?
【问题讨论】:
-
您也可以添加您的声明吗?
-
这两个函数都可以访问“矩阵”类的声明吗?
-
添加了类定义。数据在构造函数中初始化:matrix(a,b)