我想这是一个非常简单的问题,并且可能已经被多次回答过。但是,我真的很讨厌 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
是头文件,其中:
#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;
}
是C文件。正如你所看到的,非常简单的东西,但是,每当我尝试编译时,我都会得到:“错误:'name'没有在这个范围内声明”。
如果我注释掉 setName 方法,它就会编译。Iv 尝试将“名称”设置为公开,但仍然出现相同的错误。我还尝试在 setName() 中使用“this->name = _name”,这会导致“在非成员函数中无效使用 'this'”。
我不知道还要搜索什么。提前致谢。