C++ 类继承 : Functions

标签 c++ class inheritance compiler-errors undeclared-identifier

我一直在为我的物理学学位的编程模块做一些类(class),但我遇到了一些麻烦。我必须创建一个名为 Person 的类和一个名为 Employee 的子类,这样:
人.hpp:

#ifndef PERSON_HPP_
#define PERSON_HPP_

class Person {
public:
    Person(const std::string & name="Anonymous"): name(name) {;}
    ~Person() {;}

    std::string getname(){
        return name;
    }

    void setname(std::string newname) {
        name = newname;
    }

    void Print();

private:
    std::string name;
};

#endif /* PERSON_HPP_ */

个人.cpp:
void Person::Print(){
    std::string name = Person::getname;
    std::cout << name << std::endl;
}

员工.hpp:
#ifndef EMPLOYEE_HPP_
#define EMPLOYEE_HPP_

class Employee: public Person {
public:
    Employee(const std::string & name, const std::string & job) : name(name), job(job){;}
    ~Employee() {;}

    std::string getjob(){
        return job;
    }

    void setjob(std::string newjob) {
        job = newjob;
    }

    void Print() const;

private:
    std::string job;
};

#endif /* EMPLOYEE_HPP_ */

员工.cpp:
void Employee::Print(){
    Person::Print();
    std::string job = Employee::getjob;
    std::cout << job << std::endl;
}

主.cpp:
#include <iostream>
#include <string>
#include <vector>
#include "Person.hpp"
#include "Person.cpp"
#include "Employee.hpp"
#include "Employee.cpp"
#include "Friend.hpp"
#include "Friend.cpp"

int main() {
    return 0;
}

错误在我的employee.cpp 中。构建此错误时显示:
../Employee.cpp:10:6:错误:使用未声明的标识符“员工”

我意识到我可能犯了一个非常基本的错误,但是我看不到它让我感到沮丧。

任何帮助都会很棒!
提前致谢,
肖恩·库珀

注: employee.cpp 的目的是打印员工的姓名及其相关工作。

最佳答案

您的 include应该是这样的:

个人.cpp:

#include <iostream>
#include <string>
#include "Person.hpp"

员工.cpp:
#include <iostream>
#include <string>
#include "Employee.hpp"

主文件
#include <iostream>
#include <string>
#include <vector>
#include "Person.hpp"
#include "Employee.hpp"
#include "Friend.hpp"

也就是说,每个 .cpp (实现)包括相应的.hpp (接口(interface))以及所需的其他标题(如 <string> )。您的 main.cpp包括所有需要的 header ,但没有其他 .cpp文件。编译器将解析所有 .cpp单独的文件,链接器会将结果链接到可执行文件中。根据经验,永远不要包含 .cpp任何地方。

具体的错误是当编译器看到
void Employee::Print()

不知道是什么Employee是。其中Employee.hpp通过引入 Employee 来解决此问题的定义。

关于C++ 类继承 : Functions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22617027/

相关文章:

python - 如何使用 Python C/C++ 接口(interface)将实例成员函数作为 PyCFunction 类型传递

java - 矩形面向对象开发——Equals()方法

java - 在 Java 中重写泛型集合时出错

Python,覆盖继承的类方法

c++ - 使用虚拟成员从类制作 POD

c++ - 访问堆栈变量比取消引用指针慢?

c++ - 如何知道 C++ 中模板参数所需的接口(interface)/契约?

c++ - 关闭文件时会出现错误吗?

swift - 用一个函数返回几个结果

java - 使用 System.out.println() 的目的是什么