为什么要在从其他类的对象调用函数时抱怨

Why cout complaining when calling a function from an object of other class?

本文关键字:函数 调用 对象 其他 为什么      更新时间:2023-10-16

我在下面有这些作文课。 问题是,在大象.cpp中,有这样一句话: cout<<"大象做:"<<p>练习62.cpp这是主课

#include < iostream >
#include "Animal.h"
#include "Elephant.h"
int main()
{
    Animal an;
    Elephant el(an);
    el.shout();
}

动物类.cpp:动物类

#include "Animal.h"
#include <iostream>
using namespace std;
Animal::Animal()
{
   cout<<"Animal constructor"<<endl;
}
void Animal::eats()
{
 cout<<"eats"<<endl;
}
void Animal::sleeps()
{
 cout<<"sleeps"<<endl;
}
//Animal.h Animal header
#ifndef ANIMAL_H
#define ANIMAL_H
class Animal
{
 public:
        Animal();
        void eats();
        void sleeps();
};

//Elephant.cpp Elephant class definition
#include <iostream>
#include "Elephant.h"
#include "Animal.h"
using namespace std;
Elephant::Elephant(Animal an)
: animal(an)
{
}
void Elephant::shout()
{
 cout<<"Elephant do: n"<<animal.eats();
}

大象.h:大象头

#ifndef ELEPHANT_H
#define ELEPHANT_H
#include <iostream>
#include "Animal.h"
using namespace std;
class Elephant
{
  public:
         Elephant(Animal an);
         void shout();
  private:
          Animal animal;
};
#endif

有人可以解释为什么cout不接受<中的这种函数调用吗>

您在cout行中调用的函数的签名为

void eats();

这意味着它不返回任何值,因此cout没有要显示的内容。

解决此问题并将概率函数更改为:

void Elephant::shout()
{
     cout<<"Elephant do: n"; 
     animal.eats();  // has its own cout
}