重载ostream运算符会产生编译错误

时间:2015-07-21 03:58:03

标签: c++ operator-overloading

大家好我有这个代码 -

typedef struct signal_declairation{

  //these are for 2001 type declairation
  bool is_array;
  int array_start, array_end;
  PORT_ATTRIBUTE port_attribute; //port direction
  string port_type;              //logic, UDT, wire, accept every thing

  //this is common to 2001 and normal
  string port_name;

  //dumper method
  friend ostream& operator<<(ostream &out, signal_declairation &m_signal_declairation);


} SIGNAL_DECLAIRATION;

std::ostream& operator<< (ostream &out, signal_declairation &m_signal_declairation)
{
  string port_direction;
  switch(m_signal_declairation.port_attribute){
  case INPUT: port_direction = "input";
    break;
  case OUTPUT: port_direction = "output";
    break;
  case INOUT: port_direction = "inout";
    break;
  }

  if(m_signal_declairation.is_array==true){

    out << " Port Name = " << m_signal_declairation.port_name 
    << " Port Direction = " << m_signal_declairation.port_attribute
    << " Port type = " << m_signal_declairation.port_type
    << " This is an arrayed port :: Array Start = " << m_signal_declairation.array_start 
    << " Array End = " << m_signal_declairation.array_end ;



    }else{

    out << " Port Name = " << m_signal_declairation.port_name 
    << " Port Direction = " << m_signal_declairation.port_attribute
    << " Port type = " << m_signal_declairation.port_type;

  }

  return out;
}

当我尝试编译时,我得到的错误看起来像这样 -

  

parser_globals.h:在函数'std :: ostream&amp;运营商LT;≤(标准:: ostream的&安培;,   signal_declairation&amp;)':parser_globals.h:53:9:错误:不匹配   'operator&lt;&lt;'(操作数类型是'std :: ostream {aka   std :: basic_ostream}'和'const char [14]')        out&lt;&lt; &#34;端口名称=&#34; &LT;&LT; m_signal_declairation.port_name

我不知道为什么我无法将班级成员传递给&lt;&lt;如上所示。谁能帮忙???? 谢谢 拉吉

3 个答案:

答案 0 :(得分:0)

更改过载定义:

std::ostream& operator<< (ostream &out, signal_declairation &m_signal_declairation)

std::ostream& operator<< (ostream &out,const signal_declairation &m_signal_declairation) .

也不要忘记原型。

答案 1 :(得分:0)

如果您提供了完整的错误消息,而不仅仅是一小段代码,那么事情会更容易。

根据您目前提供的内容,您可能忘记为标准流添加必要的标题,例如:

#include <iostream>

这会导致编译器找不到基类型的operator<<重载或标准库中的类型。

答案 2 :(得分:0)

编译器抱怨'const char [14]')out&lt;&lt; “端口名称=”。看起来编译器看不到“端口名称 - ”作为字符串,而是将其视为字符数组。你有包括吗?