C++ 带友元函数错误的运算符重载
我正在做一项作业,它向我介绍运算符重载。我必须重载一些二进制运算符作为成员函数和友元函数。重载“+”运算符的成员函数工作正常,但重载“-”运算符的友元函数似乎很难找到成员函数能够使用的数据 类别定义:C++ 带友元函数错误的运算符重载,c++,operator-overloading,C++,Operator Overloading,我正在做一项作业,它向我介绍运算符重载。我必须重载一些二进制运算符作为成员函数和友元函数。重载“+”运算符的成员函数工作正常,但重载“-”运算符的友元函数似乎很难找到成员函数能够使用的数据 类别定义: class matrix { friend ostream& operator << (ostream&, const matrix&); friend bool operator == (const matrix &, const ma
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;
}
类矩阵
{
friend ostream&operatorfriend operator不是类的一部分。因此,它不知道大小
和范围
和数组
。必须使用对象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;
}
矩阵运算符-(常数矩阵&a,常数矩阵&b)
{
如果(a.尺寸!=b.尺寸)
抛出std::异常(…);
矩阵温度(a.尺寸,a.范围);
for(int i=0;i
友元运算符不是类的一部分。因此,它不知道大小
和范围
和数组
。必须使用对象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;
}
矩阵运算符-(常数矩阵&a,常数矩阵&b)
{
如果(a.尺寸!=b.尺寸)
抛出std::异常(…);
矩阵温度(a.尺寸,a.范围);
for(int i=0;i
尽管您的friend函数能够访问对象的私有数据,但这并不意味着属性在该函数的范围内。我的意思是,它不会像您期望的那样充当成员函数。您需要提供您正在传递的某个对象的大小。尽管您的friend函数函数将能够访问对象的私有数据,但这并不意味着属性在该函数的作用域内。我的意思是,它不会像您期望的那样充当成员函数。您需要提供所传递对象的大小。您也可以添加声明吗?这两个都很有趣Actions可以访问“matrix”类的声明?添加了类定义。数据在构造函数中初始化:matrix(a,b)您也可以添加声明吗?两个函数都可以访问“matrix”类的声明吗?添加了类定义。数据在构造函数中初始化:matrix(a,b)