c++ - 在 C++ 中重载 << 运算符?

标签 c++ operator-overloading

我正在尝试重载 << 运算符,但我遇到了一些此类错误:

passing const std::ostream' asthis' argument of `std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(const void*) [with _CharT = char, _Traits = std::char_traits]' discards qualifiers

这是我的代码:

#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 &o,lista &A)

应该是:

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

因为实际流在您写入时已被修改。

关于c++ - 在 C++ 中重载 << 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15990953/

相关文章:

c++ - 重载多维括号

c++ - 如何为 operator[] 指定返回类型?

c++ - C++ 文件 I/O 问题

c++ - C++扫描字符串的方法

java - 在 Windows、C++ 和 Java 中加密传输中的数据

c++ - 在c++中运行类成员函数的线程

c++ - 获取类中的字段数

c++ - 赋值运算符不应该返回 "empty"实例?

原始类型的 C# 重载运算符

c++ - GCC 无法区分 operator++() 和 operator++(int)