[英]Classes: compiler error «no matching function for call to “constructor”»
我是C ++的新手(也包括stackoverflow)。 不幸的是,我個人不認識C ++,因此以下問題可能太簡單了。 但是,如果我可以請一個朋友查看我的代碼,我不會發布它。 我真的很絕望。
所以,基本上,我正在嘗試鏈接3個班級:課程,老師,學生。 老師和學生的課程在課程內部“直播”。 但是,當我在Course內部創建Teacher對象時,會彈出一個編譯器錯誤:“沒有匹配的函數可調用Teacher :: Teacher()”。
我看不到任何錯誤,也無法真正掌握編譯器消息。 請在下面找到我的代碼。 對於代碼的牆,我感到很抱歉,我盡力抑制了一切。
我願意接受任何評論和批評。
提前非常感謝您。
class Teacher
{
private:
string fName;
string lName;
int age;
string address;
string city;
string phone;
public:
// Constructor & destructor
Teacher(string fName, string lName);
~Teacher();
// Setters & getters
void setName(string fNameIn, string lNameIn);
void getName();
void setAge(int ageIn);
void getAge();
void setAddress(string addressIn);
void getAddress();
void setCity(string cityIn);
void getCity();
void setPhone(string phoneIn);
void getPhone();
void GradeStudent(); // outputs an appropriate message to the console such as "Student graded"
void SitInClass(); // outputs "Sitting at front of class" for the teacher and "Sitting in main theater" for the students.
};
Teacher::Teacher(string fNameIn, string lNameIn)
{
fName = fNameIn;
lName = lNameIn;
//age = 0;
}
class Course
{
private:
string name;
Student students;
Teacher teacher;
public:
// Constructors & destructor
Course(string nameCourseIn);
//Course(string nameCourseIn, Student studentVecIn, Teacher teacherIn);
~Course();
// Setters and getters
void setName(string courseNameIn);
void getName();
void setClass(Student studentVecIn);
void setTeacher(Teacher teacherIn);
};
int main()
{
std::string name = "Intermediate C++";
Course course (name);
course.getName();
return 0;
}
您已經為Teacher
明確定義了一個構造函數,這意味着它是唯一存在的構造函數。 為了在Course
使用默認的無參數構造函數,您必須首先實現一個。
添加Teacher();
到您的Teacher.h和Teacher::Teacher(){}
到Teacher.cpp即可解決您的問題,但是您在Course
的Teacher
將需要手動初始化。
編輯:Badr El Hiouel指出,如果您不希望在默認構造函數中執行任何代碼,並且使用的是C ++ 11,則只需將Teacher() = default
添加到Teacher.h,完全從.cpp省略了它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.