gpt4 book ai didi

c++ - 我可以有一个子类的子类吗?如何继承父代和其他子类的特征而没有错误?

转载 作者:行者123 更新时间:2023-12-02 09:55:15 26 4
gpt4 key购买 nike

因此,下面是一些我正在练习继承的代码,创建了一个Employee类,并在其下创建了一些子类。它们各自都按预期运行,但是当我有Lawyer和harvardLawyer时,我希望harvardLawyer拥有与Lawyer不同的构造函数(不同的构造函数变量,工时,薪水等),但保留所有其他内容(在这种情况下,只是sue()方法)相同。

现在,我不想复制该方法,而是要继承它。我已经尝试了多种方法。

经过几次编辑...

error: no matching constructor for initialization of 'lawyer'



我该如何解决?
#include <iostream>
#include <stdio.h>
using namespace std;

class employee {
private:
int baseHours = 40;
double baseSalary = 40000.0;
int baseVacationDays = 10;
string baseVacationForm = "yellow";

public:
employee(int hours = 40, double salary = 40000.0, int days = 10,
string form = "yellow") {
baseHours = hours;
baseSalary = salary;
baseVacationDays = days;
baseVacationForm = form;
}

int getHours() { return baseHours; }
};

class lawyer : public employee {
public:
lawyer() : employee(80, 30000.0, 15, "pink") {}

string sue() { return "I'll see you in court!"; }
};

class harvardLawyer : public lawyer {
public:
harvardLawyer() : lawyer(80, 36000.0, 18, "pink pink pink pink") {}
};

int main() {
lawyer c;
harvardLawyer d;
cout << c.getHours() << "\n" << d.getHours() << "\n"; //<<d.sue();

return 0;
}

最佳答案

harvardLawyer构造函数中,您尝试调用lawyer(int, double, int, string)构造函数。但是,您的lawyer类仅具有lawyer()构造函数。您正在尝试调用一个不存在的函数。

要解决您的紧迫问题,您应该修改lawyer构造函数以采用要传递给它的所有参数。您仍然可以指定默认参数-这允许您使用零,一,二,三或四个参数(按显示的顺序)调用构造函数。你的选择。

class lawyer : public employee {
public:
lawyer(int hours = 80,
double salary = 30000.0,
int days = 15,
string tag = "pink") : employee(hours, salary, days, tag) {}

string sue() { return "I'll see you in court!"; }
};

class harvardLawyer : public lawyer {
public:
harvardLawyer() : lawyer(80, 36000.0, 18, "pink pink pink pink") {}
};

但是,尚不清楚为什么根本需要 harvardLawyer类。如果需要 harvardLawyer,只需创建一个 lawyer并传递适当的参数即可。假设 harvardLaywer不再是一个类:
int main(int argc, char** argv)
{
lawyer regular_lawyer = lawyer();
lawyer harvard_lawyer = lawyer(80, 36000.0, 18, "pink pink pink pink");
std::cout << harvard_lawyer.sue() << "\n";
}

关于c++ - 我可以有一个子类的子类吗?如何继承父代和其他子类的特征而没有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60783599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com