与 std::运算符中的"operator<<"不匹配

No match for "operator<<" in std::operator

本文关键字:lt 不匹配 operator std 运算符      更新时间:2023-10-16
#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((,它似乎无法打印返回无效的东西。

运算符<lt;在std::operator<lt;>(&std::cout(,((const-char(

像一样声明成员函数Bark

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

并称之为

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

或者不改变函数,而是像一样调用它

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

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

或者从狗窝里带走另一只狗。:(

Bark被定义为一个void函数:

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

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