[英]C++ Class Inheritance: Functions
我一直在为我的物理学学位的编程模块做一些课程,但我遇到了一些麻烦。 我必须创建一个名为 Person 的类和一个名为 Employee 的子类,这样:Person.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: error: use of undeclared identifier 'Employee'
我意识到我可能犯了一个非常基本的错误,但是我看不到它让我感到沮丧。
任何帮助都会很棒! 提前致谢,肖恩·库珀
注意employee.cpp 的目的是打印雇员的姓名及其相关的工作。
你的错误在这里:
#include "Employee.cpp"
切勿包含.cpp
文件,将它们编译为链接阶段的单独输入。
也不要忘记在Employee.cpp
文件中#include "Employee.hpp"
! 同样的事情同样适用于#include "Person.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
(接口)以及所需的其他标头(如<string>
)。 您的main.cpp
包含所有需要的头文件,但没有其他.cpp
文件。 编译器将单独解析所有.cpp
文件,链接器将结果链接到可执行文件中。 根据经验,永远不要在任何地方包含.cpp
。
具体的错误是当编译器看到
void Employee::Print()
并且不知道Employee
是什么。 包含Employee.hpp
通过引入Employee
的定义来解决这个问题。
您包含了几个 .cpp 文件,而我猜您打算包含头文件。
除了:
Person::Print(); //this call is also wrong since Print() is not static
std::string job = Employee::getjob;
getjob
是一个成员函数,你在调用成员函数时错过了()
。 同时, getjob()
不是静态成员函数,它应该与类的对象绑定。 您调用它的方式不正确。 同样的错误在这里发生:
std::string name = Person::getname; //inside Print() function of Person
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.