C ++ "Variable not declared in this scope" - again

I think this is a very simple question, and perhaps one that has been answered several times. However, I really sucked in C ++ and searched to no avail for the solution. I am very grateful for the help.

Basically:

#ifndef ANIMAL_H
#define ANIMAL_H

class Animal 
{
 public:
  void execute();
  void setName(char*);
  Animal();
  virtual ~Animal(); 

 private:
  void eat();
  virtual void sleep() = 0;

 protected:
  char* name;
};

class Lion: public Animal 
{
 public:
  Lion();

 private:
  virtual void sleep();
};



class Pig: public Animal 
{
 public:
  Pig();

 private:
  virtual void sleep();
};



class Cow: public Animal
{
 public:
  Cow();

 private:

  virtual void sleep();
};

#endif

Is the header file where:

#include <iostream>
#include "Animal.h"

using namespace std;

Animal::Animal()
{
 name = new char[20];
}
Animal::~Animal()
{
 delete [] name;
}

void setName( char* _name )
{
 name = _name;
}

void Animal::eat() 
{
 cout << name << ": eats food" << endl;
}
void Animal::execute() 
{
 eat();
 sleep();
}


Lion::Lion()
{
 name = new char[20];
}  
void Lion::sleep()
{
 cout << "Lion: sleeps tonight" << endl;
}


Pig::Pig()
{
 name = new char[20];
}   
void Pig::sleep()
{
 cout << "Pig: sleeps anytime, anywhere" << endl;
}


Cow::Cow()
{
 name = new char[20];
}
void Cow::sleep()
{
 cout << "Cow: sleeps when not eating" << endl;
}

is the C file. As you can see, things are really simple, but I get: "error:" the name was not declared in this area "whenever I try to compile.

It compiles if I comment on the setName method. Iv tried to set the "name" publicly and still get the same error. I also tried using "this-> name = _name" in setName (), which leads to the "invalid use" of this in a non-member function ".

, . .

+3
4
void setName( char* _name )
{
 name = _name;
}

void Animal::setName( char* _name )
{
  this->name = _name;
}

Animal::, this. Animal:: , setName

+8

, setName, , -. name.

setName:

void Animal::setName( char* _name )
{
  name = _name;
}
+4

"- ".

-:

void Animal::setName( char* _name )
{
 name = _name;
}
+1

" , setName"

You do not have a “setName method” in your program (with reference to a problematic definition). You have defined a completely independent global function called setNamethat is not a "method" of anything. If you want to define a method, that is, a member function of a class, you must access it using the format class_name::method_name. It will be Animal::setNamein your case.

+1
source

Source: https://habr.com/ru/post/1759924/


All Articles