【问题标题】:Friend Function = Operator Overloading of two different classFriend 函数 = 两个不同类的运算符重载
【发布时间】:2019-05-13 07:03:31
【问题描述】:

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

EROR : [Error] '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)' 必须是非静态成员函数

【问题讨论】:

  • 错误是什么?有什么问题?
  • 修改赋值的右手参数而不是左手是我很长时间以来看到的最令人困惑的事情。
  • 你错误地定义了你的operator=,看我的回答
  • 对不起我的错误我忘了写我面临的问题

标签: c++ operator-overloading friend-function


【解决方案1】:

你想要那个:

#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 &amp; operator(const TT &amp;);,其中 TT 可以是 T

operator= 和其他一些人一样不能成为非会员,请参阅https://en.cppreference.com/w/cpp/language/operators

还需要一个 getter 来获取非公共属性 seatnosno

的值

编译和执行:

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

【讨论】:

  • 我想用朋友功能来做
  • @ÂftãbBãlôçh 一些运营商不能成为非会员,请参阅en.cppreference.com/w/cpp/language/operators
  • 太棒了.. 明白了,谢谢。
  • @ÂftãbBãlôçh 当然你可以定义一个 friend 函数,但是警告你需要一个引用才能修改参数,例如friend two operator = (one,two &amp;);更贴近您的案例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多