using
- 可以用在派生类中用于恢复由 ‘继承方式’ 改变的成员访问属性如下
class Person
{
protected:
int age;
public:
Person(){}
void disp(){}
};
class Student : public Person
{
using Person::age; //这样就使本来在此类中公有的age又恢复成基类的属性了(保护protected)
using Person::disp;
}
- 为子对象初始化时如果不显示调用,此对象类的构造函数,则系统会提供一个默认的无参的构造函数
派生类构造函数
多重继承时构造次序
class student : Person, Children //默认私有继承
{
student():Children(),Person()//纵然先写children但由于先声明Person所以先构造Person.!!
}
做三件事:
- 先调用基类构造函数
- 调用子对象的构造函数(如果有的话)
- 调用自身
#include <iostream>
#include <cstring>
using namespace std;
class Person
{
protected:
string name;
int age;
public:
Person():name("boss"), age(18){
cout << "Person()..." << endl;
}
Person(string s, int a){
name = s;
age = a;
cout << "Person(string, int)..." << endl;
}
~Person(){
cout << "~person()..." << endl;
}
void disp()
{
cout << "father..." << endl;
}
};
class Student : public Person
{
public:
Student(){
code = 0;
score = 60;
cout << "Student() ..." << endl;
}
//p是Person的子对象 :构造函数执行顺序: 先基类-->后子对象对应的-->最后派生类的 constructor
Student(string s,int a, int c, double s3)
:p(s,a), Person(), code(c),score(s3){
cout << "Student(,,,)" << endl;
//Person(s, a); 老师说无法调用构造函数可这儿就可以
}
~Student(){
cout << "~Student()..." << endl;
}
void disp() const{
cout << "child..." << endl;
}
private:
int code;
double score;
Person p;
};
int main()
{
Student s2("emploee", 23, 3, 12.1);
// s2.~Person(); //也可以显示的调用析构函数
// s2.~Student();
s2.Person::disp(); //用::调用重写了的父类函数
// s2.disp();
return 0;
}