Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 其中"<<&引用;是否应使用操作员功能?_C++_Friend - Fatal编程技术网

C++ 其中"<<&引用;是否应使用操作员功能?

C++ 其中"<<&引用;是否应使用操作员功能?,c++,friend,C++,Friend,在项目中实现运算符“”功能有两种方法 1.作为非成员函数 2.作为朋友 #include<iostream> using namespace std; class xxx{ private: int x; public: xxx(int val=0):x(val){} int getx(){return x;} friend ostream& operator <<(ostrea

在项目中实现运算符“”功能有两种方法

1.作为非成员函数

2.作为朋友

  #include<iostream>
  using namespace std;
  class xxx{
     private: int x;
     public: xxx(int val=0):x(val){}
              int getx(){return x;}
             friend ostream& operator <<(ostream& o, xxx& x1);
  };
  ostream& operator<<(ostream& o, xxx& x1)
  {
    o<<x1.getx();
    return o;
  }
  ostream& operator <<(ostream& o, xxx& x1)
  {
     o<<x1.getx();
     return o;
  }
  int main(int argc, char *argv[])
  {
     xxx x1(5);
     return 0;
  }
#包括
使用名称空间std;
xxx类{
私人:int x;
公共:xxx(int val=0):x(val){}
int getx(){return x;}

friend ostream&operator这两个定义是相同的。在您的例子中,运算符没有访问类的私有或受保护成员,因此friend声明是多余的。

您似乎感到困惑——friend函数是非成员函数。因此您的
friend
声明声明了非成员函数,并且然后定义两次(非成员)函数,这是一个错误

定义(大多数)重载运算符的两种方法是作为成员函数或非成员函数。不能对同一个运算符同时执行这两种操作,如果将其定义为非成员,则它可能是朋友,也可能不是您喜欢的(
朋友
无关紧要)


至于你的最后一个问题——你不能将
操作符=
定义为非成员函数。它必须是成员函数。
友元
是不相关的。

如果你声明友元函数,那么它实际上也是一个非成员函数。如果它需要成为友元,就让它成为友元。
操作符=
不能是非成员或友元;它是必须是成员。@AlanStokes:如果将其作为成员函数,则必须像下面这样编写可能重复的“应”运算符