【问题标题】:Operator overloading with friend function error带有友元函数错误的运算符重载
【发布时间】: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)

标签: c++ operator-overloading


【解决方案1】:

友元运算符不是类的一部分。因此,它不知道sizerangearray。您必须使用对象ab。应该是这样的:

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;
}

【讨论】:

    【解决方案2】:

    虽然您的朋友函数能够访问对象的私有数据,但这并不意味着属性在该函数的范围内。我的意思是,它不会像您期望的那样像成员函数一样。您需要提供所传递对象之一的大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 2011-03-19
      • 2017-07-26
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      相关资源
      最近更新 更多