C++ 函数的继承,传入参数

C++ Inheritance of functions, passing in arguments

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

基类 :Employee
派生类 :Regular

员工.cpp

void Employee::setValue(string id, string name, double s, int n)
{
empID = id;
empName = name;
salary = s;
}

常规.cpp

void Regular::setValue(string id, string name, double s, int n) 
{
annualLeave = n;
}

Employee::setValue()只存储传入的前 3 个参数,但不存储传入的前int n个参数。

我应该在Regular::setValue()继承该setValue(),然后只是传入参数,但这次存储int nannualLeave.

我该怎么做?

或者,有没有办法在子类的基类中设置int n

你可以调用基类的实现:

void Regular::setValue(string id, string name, double s, int n) {
annualLeave = n;
return Employee::setValue(std::move(id), std::move(name), s);
}

否则,使基类多态:

struct Employee {
void setValue(string id, string name, double s, int n) {
empID = std::move(id);
empName = std::move(name);
salary = s;
setLeave(n);
}
virtual ~Employee() {}
protected:
virtual void setLeave(int) = 0;
string empID;
string empName;
double salary;
};
struct Regular: Employee {
private:
void setLeave(int n) override { annualLeave = n; }
int annualLeave;
};

如果需要保留单签名 setValue 函数,可以这样做:

-

包括:

#include <any>
#include <map>
#include <string>

-

员工.h:

class CEmployee
{
protected:
virtual void setValue(std::map<std::string, std::any> &info);
int m_empID = 0;
std::string m_empName = {''};
int m_salary = 0;
}

员工.cpp:

void CEmployee::setValue(std::map<std::string, std::any> &info)
{
std::any item;
item = info["empID"];
if (item.has_value())
m_empID = std::any_cast<int>(item); // int
item = info["empName"];
if (item.has_value())
m_empName = std::any_cast<std::string>(item); // std::string 
item = info["salary"];
if (item.has_value())
m_salary = std::any_cast<int>(item); // int 
}

-

Regular.h:

class CRegular : public CEmployee
{
public:
void setValue(std::map<std::string, std::any> &info) override;
protected:
std::string m_annualLeave = {''};
}

常规.cpp:

void CRegular::setValue(std::map<std::string, std::any> &info)
{
std::any item;
CEmployee::setValue(info);
item = info["annualLeave"];
if (item.has_value())
m_annualLeave = std::any_cast<std::string>(item); // std::string 
}

-

并这样称呼它:

void MyClass::HardcodedExample()
{
CRegular regular_employee;
std::map<std::string, std::any> info, update;
info["empID"] = { 100 };
info["empName"] = { std::string("Trump") };
info["salary"] = { 1000000 };
info["annualLeave"] = { std::string("29 Jul 2018") };
regular_employee.setValue(info); // Set all info
// Or:
update["annualLeave"] = { std::string("29 Dec 2018") };
regular_employee.setValue(update); // Update just "annualLeave"
// Or:
update["salary"] = { 1200000 };
update["annualLeave"] = { std::string("04 Jul 2018") };
regular_employee.setValue(update); // Update "salary" & "annualLeave"
}

-

否则,将 3 个参数的 setValue 设置为基类,并将 4 个参数设置为派生类(使用 3 个参数调用基类并自行设置第 4 个参数( - 类似于@RemyLebeauis提供的解决方案 - 是一个更好的解决方案。

-

最好使用 #define/枚举键而不是字符串键(并相应地更改映射的键类型(,但这是一个不同的问题。