C++中的继承

Inheritance in C++?

本文关键字:继承 C++      更新时间:2023-10-16

我正在努力学习继承。我试着从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。(我冒昧地修复了你的压痕)。以类似的方式,您需要datenumber的声明。

您还没有声明cin需要读入的变量。

只需添加

string name;
int number;
string date;

在函数main