C++ 没有合适的默认构造函数可用

发布于 2019-12-04  143 次阅读


#include <iostream>
class Student
{
private:
    int id;
    char *name;
    int age;
public:
    Student(int the_id,char *the_name,int the_age)
    {
        id = the_id;
        name = the_name;
        age = the_age;
    }
    int getage()
    {
        return age;
    }
    char * getname()
    {
        return name;
    }
    int getid()
    {
        return id;
    }
};
class Item :public Student
{
public:
    Item()
    { //此处报错“没有合适的默认构造函数可用”

    }
    float ave()
    {

    }
private:
    float Chinese,math,English;
};
int main()
{
    char name[20] = "Xiao Ming";
    Student xiaoming = Student(101011,name,18);
    std::cout<<xiaoming.getname()<<":"<<xiaoming.getid()<<" "<<xiaoming.getage();
}

解决方法(一):
Student类中添加一个不带参数的默认构造函数!

...
class Student
{
public:
    Student(void)
    {
    }
    Student(int the_id, char* the_name, int the_age)
    {
        id = the_id;
        name = the_name;
        age = the_age;
    }
    ...

解决方法(二):

...
class Student
{
public:
    Student(int the_id=0, char* the_name=0, int the_age=0)
    {
        id = the_id;
        name = the_name;
        age = the_age;
    }
...

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。