【问题标题】:no match for 'operator<<' in 'std::operator'std::operator 中的 'operator<<' 不匹配
【发布时间】:2014-09-15 23:55:21
【问题描述】:
#include <iostream>

using namespace std;


    class critter{
    public :   // public section
          critter (int hunger =0) ;
        int gethunger() const ;
        void sethunger (int hunger) ;
    private :
         int m_hunger ;

    };

    critter :: critter (int hunger) :
      m_hunger (hunger)
      {
          cout << "new critter has been born" << endl ;
       }
 int critter :: gethunger() const
    {
        return m_hunger ;
    }

    void critter :: sethunger (int hunger)
    {
        if (hunger<0) {
            cout << "you can not set a negative number to hunger" << endl  ;

        }
 else {
    m_hunger=hunger ;
 }
    }
    int main ()
    {

        critter crit(5);
          cout << "calling gethunger()"<<crit.gethunger()<<endl ;

            cout << "calling sethunger ()" << crit.sethunger(-1) << endl ;
             return 0 ;

    }

我收到以下错误: 'std::operator((* & std::cout), ((const char*)"calling sethunger ()") 中的 'operator

在这一行:

{cout

请告诉我为什么编译器不打印{you can not set a negative number to hang}

【问题讨论】:

  • sethunger 应该返回一个字符串并且没有输出。或者你的 main 不应该尝试打印这个函数......
  • 您不能只用int 替换void 返回类型,然后什么都不返回。这没有任何意义。
  • 我猜您想“调试打印”您现在正在调用该函数并且不需要打印任何返回值的事实(因为没有任何返回值)。您可以简单地在第二行中编写调用而没有任何输出,或者您可以破解:cout &lt;&lt; "..." &lt;&lt; (crit.sethunger(-1), "") &lt;&lt; endl; -- 说明:在括号内,您首先调用该函数(丢弃此处甚至不存在的任何返回值)。然后(在逗号之后)提供可以打印的内容(空字符串)。
  • 您通过打印crit.sethunger(-1) 的返回值到底想完成什么?也许如果你能解释你想要做什么,它会帮助别人为你提供一个很好的答案。
  • @indiv 我猜他认为他需要将其写入cout 才能看到sethunger 可能生成的错误消息。但这是一个错误的假设。 (但如果它以字符串形式返回错误就会出现这种情况)

标签: c++ class oop


【解决方案1】:

您的猜测是正确的:void 无法打印。您应该做的是在打印消息后致电sethunger()

cout << "calling sethunger ()" << endl;
crit.sethunger(-1);

关于您的更新: 请告诉我为什么编译器不打印{you can not set a negative number to hang}

你写的信息不是由编译器打印出来的,它们是由编译好的程序打印出来的。而且只要你的代码不编译,就没有程序可以写消息。

【讨论】:

    【解决方案2】:
    cout << "calling sethunger ()" << crit.sethunger(-1) << endl ;
    

    sethunger() 成员函数返回一个 void。当然,不能在 std::cout 上写 void。

    【讨论】:

    • OP 已经在问题中这样说:“我猜错误告诉我编译器不知道如何向 ostream 插入 void”
    • 全世界只有一个人可以“让这段代码工作”。那就是你。只有你知道它应该做什么。已向您解释了此特定错误消息的原因。 std::ostream 不会在 void 上重载。现在,您需要弄清楚应该发生什么,而不是那样,并相应地更改代码。
    猜你喜欢
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 2016-08-28
    • 2012-03-02
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多