首先要了解子类调用构造函数过程:父类构造函数–>子类构造函数
1.父类有默认构造函数,子类未显示调用时,子类自动调用父类的默认构造函数;
#include <iostream>
using namespace std;
class Father
{
public:
Father()
{
cout << "父类默认构造函数!\n";
}
};
class Children : public Father
{
public:
Children()
{
cout << "子类构造函数!\n" << endl;
}
};
int main(int argc, char** argv)
{
Children rec;
return 0;
}
2.父类有默认构造函数,子类显示调用时,子类自动调用父类的默认构造函数;
#include <iostream>
using namespace std;
class Father
{
public:
Father()
{
cout << "父类默认构造函数!\n";
}
};
class Children : public Father
{
public:
Children() : Father()
{
cout << "子类构造函数!\n" << endl;
}
};
int main(int argc, char** argv)
{
Children rec;
return 0;
}
3.父类没有默认构造函数,子类显示调用时,子类会调用系统为父类生成的默认构造函数;
#include <iostream>
using namespace std;
class Father
{
public:
// Father()
// {
// cout << "父类默认构造函数!\n";
// }
};
class Children : public Father
{
public:
Children() : Father()
{
cout << "子类构造函数!\n" << endl;
}
};
int main(int argc, char** argv)
{
Children rec;
return 0;
}
4.父类没有默认构造函数,子类未显示调用时,子类会调用系统为父类生成的默认构造函数;
#include <iostream>
using namespace std;
class Father
{
public:
// Father()
// {
// cout << "父类默认构造函数!\n";
// }
};
class Children : public Father
{
public:
Children()// : Father()
{
cout << "子类构造函数!\n" << endl;
}
};
int main(int argc, char** argv)
{
Children rec;
return 0;
}
5.父类有带参数的构造函数,也有默认构造函数,子类未显示调用父类构造函数时,子类会调用父类默认构造函数;
#include <iostream>
using namespace std;
class Father
{
public:
Father()
{
cout << "父类默认构造函数!\n";
}
Father(int nNum)
{
cout << "父类传参构造函数!\n";
}
};
class Children : public Father
{
public:
Children()
{
cout << "子类构造函数!\n" << endl;
}
};
int main(int argc, char** argv)
{
Children rec;
return 0;
}
6.父类有带参数的构造函数,也有默认构造函数,子类显示调用父类一种构造函数时,子类会调用父类该种构造函数;
#include <iostream>
using namespace std;
class Father
{
public:
Father()
{
cout << "父类默认构造函数!\n";
}
Father(int nNum)
{
cout << "父类传参构造函数!\n";
}
};
class Children : public Father
{
public:
Children() : Father(1)
{
cout << "子类构造函数!\n" << endl;
}
};
int main(int argc, char** argv)
{
Children rec;
return 0;
}
错误方式:
父类仅写了带参数的构造函数,没写不带参数的默认构造函数时,而子类又没有显示调用父类构造函数时,编译失败。因为父类写了构造函数,系统就不会为父类生成默认构造函数,子类想调用父类的默认构造函数时找不到;
#include <iostream>
using namespace std;
class Father
{
public:
// Father()
// {
// cout << "父类默认构造函数!\n";
// }
Father(int nNum)
{
cout << "父类传参构造函数!\n";
}
};
class Children : public Father
{
public:
Children()// : Father()
{
cout << "子类构造函数!\n" << endl;
}
};
int main(int argc, char** argv)
{
Children rec;
return 0;
}
如果觉得子类调用父类构造函数情况太多,不好记忆,那么每次写子类构造函数时最好显示调用父类构造函数!