子类声明“没有合适的默认构造函数可用”[关闭]

问题描述 投票:0回答:1

我创建了一个带有默认构造函数和子类的类。当我尝试使用默认构造函数创建子类的实例时,出现错误 C2512(没有合适的默认构造函数可用)和 E0289(构造函数“Faculty::Faculty”的实例没有与参数列表匹配)。

#include <string>
#include <memory>

using namespace std;

//Enum class header and body
enum class Discipline {COMPUTER_SCIENCE, MUSIC, CHEMISTRY};

class Person {
protected:
    string name;
public:
    //Constructors
    Person() {
        setName("Belethor");
    }

    Person(const string& pName) {
        setName(pName);
    }

    //Getters and Setters
    void setName(const string& pName) {
        name = pName;
    }

    string getName() const {
        return name;
    }
};

class Student : public Person {
private:
    Discipline major;
    shared_ptr<Person> advisor;
public:
    //Constructors
    Student(const string& name, Discipline d, const shared_ptr<Person> adv) : Person(name) {
        major = d;
        advisor = adv;
    }

    //Getters and Setters
    Discipline getMajor() const {
        return major;
    }

    void setMajor(Discipline d) {
        major = d;
    }

    shared_ptr<Person> getAdvisor() const {
        return advisor;
    }

    void setAdvisor(shared_ptr<Person> p) {
        advisor = p;
    }
};

class Faculty : public Person {
private:
    Discipline department;
public:
    //Constructors
    Faculty(const string& fname, Discipline d) : Person(fname) {
        department = d;
    }

    //Getters and Setters
    Discipline getDepartment() const {
        return department;
    }

    void setDepartment(Discipline d) {
        department = d;
    }
};

class TFaculty : public Faculty {
private:
    string title;
public:
    //Constructors
    TFaculty(const string& fname, Discipline d, string title) : Faculty(fname, d) {
        this->title = title;
    }

    //Getters and Setters
    string getName() const {
        return title + name;
    }

    void setTitle(const string& title) {
        this->title = title;
    }
};
#include <iostream>
#include "college.h" 

using namespace std;

const string dName[] = {
    "Computer Science", "Music", "Chemistry"
};

int main()
{
    shared_ptr<Faculty> prof = make_shared<Faculty>();
    return 0;
}

Faculty
是否没有继承类
People
中定义的默认构造函数?

c++ inheritance constructor subclass default-constructor
1个回答
1
投票

正如评论中所指出的,不,您已经明确指出

Faculty
只有一个构造函数,并且需要两个参数。现在,您可以为这些参数提供默认值,尽管我不确定在这种情况下什么值作为默认值有意义。

你的类后面也需要跟一个分号,你可以在你的成员初始化列表中初始化

department

        Faculty(const string& fname, Discipline d) 
        : Person(fname), department(d) 
        { }
© www.soinside.com 2019 - 2024. All rights reserved.