C++中的继承
Inheritance in C++?
我正在努力学习继承。我试着从Employee派生出一个名为ProductionWorker的类。我正在努力遵循这个网站给出的模式。然而,继承似乎不起作用,因为我在主函数中遇到错误,说名称、数字和日期没有在这个范围内设置。代码出了什么问题?
程序.cpp:
#include <iostream>
#include <string>
#include "employee.h"
using namespace std;
int main() {
ProductionWorker worker;
cout<<"What is the employee name?"<<endl;
cin>>name;
worker.setName(name);
cout<<"What is the employee number?"<<endl;
cin>>number;
worker.setNumber(number);
cout<<"What is the employee hire date?"<<endl;
cin>>date;
worker.setDate(date);
cout<<"Employee Information:"<<endl;
cout<<worker.getName()<<endl;
cout<<worker.getNumber()<<endl;
cout<<worker.getDate()<<endl;
cout<<worker.getShift()<<endl;
cout<<worker.getPayRate()<<endl;
return 0;
}
employee.h:
#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_
#include <string>
#include <iostream>
using namespace std;
class Employee{
protected:
string name;
int number;
string date;
public:
Employee(string a="", int b=0, string c=""){
name=a;
number=b;
date=c;
}
void setName(string);
void setNumber(int);
void setDate(string);
string getName();
int getNumber();
string getDate();
};
class ProductionWorker: public Employee{
private:
int shift;
double pay;
public:
ProductionWorker(int d=1, double e=10.0, string a="", int b=0, string c=""):Employee(a, b, c){
shift=d;
pay=e;
}
int getShift();
double getPayRate();
};
employee.cpp:
#include <string>
#include <iostream>
#include "employee.h"
using namespace std;
//EMPLOYEE
void Employee::setName(string a){
name=a;
}
void Employee::setNumber(int b){
number=b;
}
void Employee::setDate(string c){
date=c;
}
string Employee::getName(){
return name;
}
int Employee::getNumber(){
return number;
}
string Employee::getDate(){
return date;
}
//PRODUCTION WORKER
int ProductionWorker::getShift(){
return shift;
}
double ProductionWorker::getPayRate(){
return pay;
}
我认为在Program.cpp中使用名称、编号和日期之前,您应该声明它。您试图将输入输入到编译器还不知道的符号中。
您的错误与继承无关:
int main() {
ProductionWorker worker;
cout<<"What is the employee name?"<<endl;
cin>>name;
您正在读取一个名为name
的变量,但范围内没有此类变量(即在main()
函数本身或全局声明)。虽然name
是Employee类的成员,但不能以这种方式使用它。(考虑一下:编译器如何知道要为哪个Employee实例设置name
?当然,如果可以直接读取实例变量,那么之后就不需要调用worker.setName(...)
了)。
您应该通过指定name
的类型来将其声明为本地变量:
int main() {
string name;
ProductionWorker worker;
cout<<"What is the employee name?"<<endl;
cin>>name;
现在cin>>name;
读入在main()
函数中声明的局部变量name
。(我冒昧地修复了你的压痕)。以类似的方式,您需要date
和number
的声明。
您还没有声明cin
需要读入的变量。
只需添加
string name;
int number;
string date;
在函数main
。
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 如何在QT Creator上将QWidget声明为继承类的对象