友元函数 = 两个不同的运算符重载 class

Friend Function = Operator Overloading of two different class

我正在练习运算符重载,我已经完成了数百次运算符重载,但是如果我将这段代码与旧代码语法(符合良好)进行比较,我发现语法没有变化,请指导 me.Thanks

错误:[错误]'two operator=(one, two)'必须是非静态成员函数

#include<iostream>
using namespace std;
class two;
class one{
    int sno;
    public:
        one()
        {
            sno=312;
        }

    friend two operator =(one,two);
};  
    //b b1; b1=a.seatno;
class two{
    int seatno;
    public:
        two(){seatno=0;
        }
        friend two operator = (one,two);

};

    two operator = (one a1,two b1)
    {
        b1.seatno=a1.sno;
        return b1;
    }
int main()
{
    one a1;
    two b1;
    b1=a1;
}

[错误]'two operator=(one, two)'必须是非静态成员函数

你想要那个:

#include<iostream>
using namespace std;

class two;

class one{
    int sno;
  public:
    one() : sno(312) {}
    //one & operator =(const two & t);
    int getSno() const { return sno; }
};  

class two{
    int seatno;
  public:
    two() : seatno(0) {}
    two & operator = (const one & o);
    int getSeatno() const { return seatno; }
};

two & two::operator =(const one & o)
{
  seatno = o.getSno();
  return *this;
}

int main()
{
  one a1;
  two b1;

  cout << b1.getSeatno() << endl;
  b1=a1;
  cout << b1.getSeatno() << endl;
}

对于类型 T operator= 的签名是 T & operator(const TT &); 其中 TT 可以是 T.

operator=因为有些人不能是non-member,见https://en.cppreference.com/w/cpp/language/operators

另请注意,需要 getter 才能获取非 public 属性 seatnosno[=31 的值=]

编译与执行:

/tmp % g++ -pedantic -Wall -Wextra a.cc
/tmp % ./a.out
0
312