派生类不能继承基类的构造函数,若想通过派生类来对基类的private的变量成员进行初始化则需要:
通过派生类的构造函数来调用基类的构造函数完成基类成员变量的初始化.
看下面的例子:
#include <iostream>
#include<string>
using namespace std;
class People {
private:
char *m_name;
int m_age;
public:
People(char*, int);
};
People::People(char* name,int age):m_name(name),m_age(age){}
class Student : public People {
//此处的public是将其基类:People 的成员以其在People内的级别于Student中继承,
//即成员在基类中是什么级别就以什么级别被派生类继承.protected则是将public级别的成员改为protected被派生类继承,private则是
//全变成private被派生类继承
private:
float m_score;
public:
Student(char* name, int age, float score);
//void display();
};
Student::Student(char*name,int age,float score):People(name,age),m_score(score){
cout << " 姓名: " << name << " 年龄: " << age << " 成绩: " << score << endl;
} //在此处调用基类的构造函数,可调换基类构造函数的顺序,当然相应的形参位置也要变.
/*void Student::display() {
cout <<" 姓名: "<< m_name << " 年龄: " << m_age << " 成绩: " << m_score << endl;
}*/
int main()
{
Student *pstu = new Student("Chan",21,99);
//pstu->display();
return 0;
}
错误用法:
Student::Student(char *name, int age, float score){
People(name, age);
m_score = score;
} //error
因为派生类没有继承基类的构造函数,所以不能调用基类的构造函数.
构造函数调用顺序:
先是调用基类的构造函数,然后再调用派生类的构造函数,多继承亦然.
注意事项:多继承如 A -- B -- C 只能直接调用基类构造函数,不能间接调用基类构造函数,即B可调用A,但C不可调用A.
/*C++ 这样规定是有道理的,因为我们在 C 中调用了 B 的构造函数,B 又调用了 A 的构造函数,相当于 C 间接地(或者说隐式地)调用了 A 的构造函数,如果再在 C 中显式地调用 A 的构造函数,那么 A 的构造函数就被调用了两次,相应地,初始化工作也做了两次,这不仅是多余的,还会浪费CPU时间以及内存,毫无益处,所以 C++ 禁止在 C 中显式地调用 A 的构造函数。 */
通过派生类创建对象时必须要调用基类的构造函数,这是语法规定。换句话说,定义派生类构造函数时最好指明基类构造函数;如果不指明,就调用基类的默认构造函数(不带参数的构造函数);如果没有默认构造函数,那么编译失败。
请看下面的例子:
#include<iostream>
#include<string>
using namespace std;
class People {
private:
char* m_name;
int m_age;
public:
People();
People(char*, int);
};
People::People(char* name, int age) :m_name(name), m_age(age) {};
People::People() :m_name("xxxx"), m_age(00) {};
class Student : public People {
private:
float m_score;
public:
Student();
Student(char *name, int age, float score);
};
Student::Student() :People(), m_score(0) {
cout << "姓名:xxxx" << " 年龄:00" << " 成绩:0" << endl;
};
Student::Student(char* name, int age, float score) :People(name, age), m_score(score) {
cout << "姓名:" <<name<< " 年龄:" <<age<< " 成绩:" <<score<< endl;
};
int main() {
Student *pstu = new Student;
Student *pstu1 = new Student("陈东",16,88.5);
return 0;
}
如果将People(name, age)去掉,也会调用默认构造函数.(上面代码执行后看不出来,需修改People类的private为protected,再在student类中写void display())
1 void Student::display(){
2 cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<"。"<<endl;
3 }
附:https://blog.csdn.net/qq_23996069/article/details/89344816
转载来源:http://c.biancheng.net/view/2276.html
来源:https://www.cnblogs.com/ArrowToLanguage/p/12284572.html