不匹配"运营商<<"在std :: operator中

时间:2015-06-23 20:33:03

标签: c++

#include <iostream>
#include <string>
using namespace std;

// your code
class Dog {
public:
   int age;
   string name, race, voice;

   Dog(int new_age,string new_name,string new_race,string new_voice);
   void PrintInformation();
   void Bark();
};

    Dog::Dog(int new_age,string new_name,string new_race,string new_voice) {
        age = new_age;
        name = new_name;
        race = new_race;
        voice = new_voice;
    }

    void Dog::PrintInformation() {
        cout << "Name: " << name;
        cout << "\nAge: " << age;
        cout << "\nRace: " << race << endl;
    }

    void Dog::Bark(){
        cout << voice << endl;
    }


int main()
{
  Dog buffy(2, "Buffy", "Bulldog", "Hau!!!");
  buffy.PrintInformation();
  cout << "Dog says: " << buffy.Bark();
}

我是C ++中的新手,我无法弄清楚错误。我在buffy.Bark()收到错误,似乎无法打印返回void的内容。

  

不匹配运营商&lt;&lt;在std :: operator&lt;&lt; &gt;(&amp; std :: cout),((const char

2 个答案:

答案 0 :(得分:2)

声明成员函数Bark,如

std::string Dog::Bark(){
    return  voice;
}

并将其称为

cout << "Dog says: " << buffy.Bark() << endl;

或者不要更改功能,而是像

一样调用它
cout << "Dog says: "; 
buffy.Bark();

因为函数的返回类型为void。

或者从狗窝里带走另一条狗。:)

答案 1 :(得分:0)

Bark被定义为void函数:

void Dog::Bark(){
    cout << voice << endl;
}

这意味着尝试在cout << buffy.Bark()中执行main尝试输入void类型变量,这是不可能的。您可能只是意味着buffy.Bark();,它已经为您输出了。