Jub*_*see 2 c++ variables scope protected out
我想这是一个非常简单的问题,可能是一个已经多次回答的问题.但是,我真的对C++感到厌烦,并且搜索无法找到解决方案.我真的很感激帮助.
基本上:
#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
Run Code Online (Sandbox Code Playgroud)
是头文件,其中:
#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;
}
Run Code Online (Sandbox Code Playgroud)
是C文件.正如你所看到的,非常简单的东西,但是,每当我尝试编译时,我得到:"错误:'name'未在此范围内声明".
如果我注释掉setName方法,它会编译.我尝试将'name'设置为public并仍然得到相同的错误.我也尝试在setName()中使用"this-> name = _name",这导致"在非成员函数中无效使用'this'".
我不知道还有什么可以搜索的.提前致谢.
void setName( char* _name )
{
name = _name;
}
Run Code Online (Sandbox Code Playgroud)
应该
void Animal::setName( char* _name )
{
this->name = _name;
}
Run Code Online (Sandbox Code Playgroud)
你需要有Animal::,如果你使用的this参数.没有Animal::它认为你只是创建一个名为的新的全局函数setName