why assigment operator can not be frined

在尝试将一个结构体赋值给字符串时遇到问题,原本期望通过重载赋值运算符来解决,但编译报错。原因是C++中不允许将赋值运算符声明为独立的非成员函数,以防翻译单元中行为发生变化,导致不一致。解决方案是直接覆盖原有函数,并在需要的地方调用相应版本。
摘要由CSDN通过智能技术生成

博客搬家,原地址:https://langzi989.github.io/2017/03/21/why-assigment-operator-can-not-be-frined-function/

this is a problem in my work and I have find th solution on stackoverflow,so recorder here

problem description

When I refactor my object, I have a problem which need to change the return value
of and function std::string to a struct data, but I don’t want to change my code
where the function be used, so I want to overload the assignment operator which
will assign a struct to string.The code is as follows:

#include <string>
class data_struct{
   
  friend std::string operator = (std::string& s, data_struct& d);
private:
  bool success{
   false};
  std::string message{
   ""};
public:
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值