【问题标题】:C++ Header File Error: Base Class UndefinedC++ 头文件错误:基类未定义
【发布时间】:2018-04-24 11:50:55
【问题描述】:

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

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

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

主 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

【问题讨论】:

  • 在使用之前不应该在animal.h中声明COLOR吗?
  • COLOR 在 cpp 文件中定义,在标头中不可见,您在标头文件中使用 coutstd 命名空间中的其他内容,而没有正确添加 ::std::

标签: c++ visual-studio visual-studio-2010 visual-c++


【解决方案1】:

同时使用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++ 中,每个类型或函数都必须先声明或定义,然后再使用,反之亦然。

【讨论】:

  • 这不是多余的,同时使用pragma once 和header guards 可能会产生与只使用其中一个不同的效果。
  • @VTT,你说的是典型的实际用法吗?
  • @ArashMohammadi "不要忘记头文件中的using namespace std ..."我能想到的最糟糕的建议。
  • @user0042,我完全同意。但他必须写下所有std:: 标头。只是一种使代码可编译的快速方法。
  • @ArashMohammadi Better “快捷方式”using std::string;
猜你喜欢
  • 1970-01-01
  • 2014-09-03
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多