C++头文件错误:基类未定义



我目前对在我的启动项目中包含头文件感到非常沮丧。 到目前为止,我有一个链接到我的基本文件的头文件,并且不断收到编译无法读取我的基类的相同错误。

我认为读取头文件有问题。我该怎么办?

更新现在它显示构建编译错误

主 cpp 文件

#include <string>
#include "animal.h"
using namespace std;
enum COLOR { Green, Blue, White, Black, Brown };
int main() {
cout << "Starting" << endl;
int value = 0; Mammal *zoo[3];
int i = 0;
cout << "Program exiting …. " << endl;
return 0;
}

头文件

#include <iostream>
#include <string>
#ifndef HEADER_H
#define HEADER_H
using namespace std;
enum COLOR { Green, Blue, White, Black, Brown };
class Animal {
public:
Animal() {
    cout << "constructing Animal object " << _name << endl;
}
~Animal() {
    cout << "destructing Animal object " << _name << endl;
}
Animal(std::string n, COLOR c) {
    _name = n; _color = c;
    cout << "constructing " << _name << " Color " <<
        endl;
}
virtual void speak() const { cout << "Animal speaks " << endl; }
//void speak() const { cout << "Animal speaks " << endl; }
virtual void move() = 0;
void setName(std::string n) { _name = n; }
void setCOLOR(COLOR c) { _color = c; }
private:
std::string _name; COLOR _color;
};
class Mammal : public Animal {
public:
Mammal() {}
Mammal(std::string n, COLOR c) {
    setName(n);
    setCOLOR(c);
    cout << "constructing Mammal object " <<  endl;
}
~Mammal() { cout << "destructing Mammal object " << endl; }
};
#endif

一起使用pragma once并一起包含守卫是多余的。删除任何一个。

如果在标头中使用string,请不要忘记它需要std::前缀。

COLOR必须移动到头文件。

// #pragma once
#ifndef HEADER_H
#define HEADER_H
using namespace std;
enum COLOR { Green, Blue, White, Black, Brown };

您还需要定义setName

结语:

在 C 和 C++ 中,每个类型或函数必须首先声明或定义,然后使用,反之亦然。

最新更新