【问题标题】:error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'void' (or there is no acceptable conversion)错误 C2679:二进制“<<”:未找到采用“void”类型右侧操作数的运算符(或没有可接受的转换)
【发布时间】:2014-04-22 22:11:41
【问题描述】:

我不确定是什么问题。它给了我错误:

error C2679: binary '
我重载了

#ifndef ANIMAL_H_
#define ANIMAL_H_ 
#include <iostream> 
#include <string>
using namespace std;

static int counter;
static int getAnimalCount() { return counter; }

class Animal {
    protected:
       string *animalType;
    public:
       virtual void talk() = 0;
       virtual void move() = 0;
       string getAnimalType() { return *animalType; }

               //PROBLEM RIGHT HERE V

       friend ostream& operator<<(ostream&out, Animal& animal) {
           return out << animal.getAnimalType() << animal.talk() << ", " << animal.move();
       };
       ~Animal() {
           counter--;
           animalType = NULL;
       }
 };
 class Reptile : public Animal { 
     public:
         Reptile() { animalType = new string("reptile"); };
 };
 class Bird : public Animal {
     public:
         Bird() { animalType = new string("bird"); };
 };
 class Mammal : public Animal{
     public:
         Mammal() { animalType = new string("mammal"); };
 };
 #endif /* ANIMAL_H_ */

【问题讨论】:

    标签: c++ overloading


    【解决方案1】:

    virtual void talk() = 0; 指定返回类型为void 的函数。这意味着它不会返回任何东西。当您将Animal::move 定义为virtual void move() = 0; 时,也会发生同样的情况。

    out &lt;&lt; animal.getAnimalType() &lt;&lt; animal.talk() &lt;&lt; ", " &lt;&lt; animal.move(); 尝试打印animal.talk() 的结果和animal.move() 的结果——两者都不存在(记住,talk()move() 都不返回任何值!)

    【讨论】:

      【解决方案2】:

      您的重载 &lt;&lt; 运算符如下所示:

      return out << animal.getAnimalType() << animal.talk() << ", " << animal.move();
      

      首先,talk()move() 方法返回 void。您不能打印 void。

      【讨论】:

      • getAnimalType() 一个成员函数。
      【解决方案3】:

      重点是代码生成器。我有类成员 Dot.printX(),在输出流中我使用了cout&lt;&lt;Dot.printX&lt;&lt;endl;,这样会导致错误。

      添加printX() 将解决问题!

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多