重载 << C++ 中的运算符?

Overloading << operator in c++?

本文关键字:lt 运算符 C++ 重载      更新时间:2023-10-16

我试图重载<<操作符,但我得到一些这样的错误:

传递const std::ostream' as的this'参数"std:: basic_ostream<_CharT _Traits>,std:: basic_ostream<_CharT,_Traits>::operator<<(const void*) [with _CharT = char, _Traits = std::char_traits]'丢弃限定符

下面是我的代码:
#include<iostream>
using namespace std;
class nod{
    protected: 
    int info;
    nod *next;
    friend class lista;
    friend const ostream &operator<<(const ostream &,lista&);
};
class lista
{nod *first, *last;
 public:
 lista()
 {first=new nod;
  last=new nod;
  first=last=NULL;}   
 void insert(int);
 // void remove();
  void afisare();
 nod *get_first(){ return first;};
};
void lista::insert(int x)
{    nod *nou=new nod;    
     nou->info=x;    
     if(!first)
                     first=last=nou;
     else         
                     nou->next=first;  
     first=nou;
     last->next=first;}

const ostream &operator<<(const ostream &o,lista &A)
{nod *curent=new nod;
o<<"Afisare: ";
curent=A.get_first();
if(curent)
          o<<curent->info<<" ";
curent=curent->next;
while(curent!=A.get_first())
          {o<<curent->info<<" ";
          curent=curent->next;}
return o;
}

int main()
{lista A;
A.insert(2);
A.insert(6);
A.insert(8);
A.insert(3);
A.insert(5);
cout<<A;
system("pause");
return 0;}    

这个const ostream &operator<<(const ostream & 0,list &A)

应:

ostream &operator<<(ostream &o,lista &A)

作为实际流在写入时被修改。