一、继承
子类会继承父类所有的属性跟方法。(重点)
class Person {
public:
string name;
char gender;
int age;
};
class Student : public Person {
public:
string major;
};
二、private&protexted&public(重点)
private: 成员变量和函数只在自己的类里面可以访问。
protexted:成员变量和函数只在自己的类和子类里面可以访问。
三、公有继承
四、私有继承
五、保护继承
六、三种继承方式的综合实例
class Father {
public:
int a;
protected:
int b;
private:
int c;
};
class Son1 : public Father {
public:
void show() {
cout << a << endl;//public
cout << b << endl;//protected
cout << c << endl;//父类的private,访问不到
}
};
class Son2 : protected Father {
public:
void show() {
cout << a << endl;//protected
cout << b << endl;//protected
cout << c << endl;//父类的private,访问不到
}
};
class Son3 : private Father {
public:
void show() {
cout << a << endl;//private
cout << b << endl;//private
cout << c << endl;//父类的private,访问不到
}
};
class GrandSon : public Son3 {
public:
void show() {
cout << a << endl;
cout << b << endl;
cout << c << endl;
//三个都访问不到
}
};
void main() {
Father f;
cout << f.a << endl;
cout << f.b << endl;//访问不到
cout << f.c << endl;//访问不到
Son1 s1;
cout << s1.a << endl;
cout << s1.b << endl;//访问不到
cout << s1.c << endl;//访问不到
Son2 s2;
cout << s2.a << endl;
cout << s2.b << endl;
cout << s2.c << endl;
//三个都访问不到
Son3 s3;
cout << s3.a << endl;
cout << s3.b << endl;
cout << s3.c << endl;
//三个都访问不到
}
七、重名(冲突)与隐藏
class Father {
public:
int age;
Father() : age(18) {}
void show() {
cout << "Father::show()" << endl;
}
void show(int a) //函数重载
{
cout << "Father::show(int a)" << endl;
}
};
class Son : public Father {
public:
int age;//与父类属性重名
Son() : age(28) {}
void show() //与父类方法重名
{
cout << "Son::show()" << endl;
}
};
void main() {
Son s;
cout << s.age << endl;//28,把父类的属性值隐藏了
cout << s.Father::age << endl;//18,重名时访问父类属性的方式
cout << s.Son::age << endl;//28
s.show();//Son::show(),把父类的方法隐藏了
s.Father::show();//Father::show(),重名时访问父类方法的方式
s.Son::show();//Son::show()
s.show(100);//报错,就算父类中函数重载了还是会被隐藏
s.Father::show(100);//Father::show(int a)
}
八、子类与父类的构造与析构顺序
创建一个子类对象时,构造时先构造父类,再构造子类,析构时先析构子类,再析构父类。(可能会考)
九、类的大小
class Father//父类
{
public:
int id;
int age;
int bank_card;
};//sizeof(f)=12
class Son : public Father //子类
{
public:
int n_toy;
};//sizeof(s)=12+4=16
class Father //父类
{
public:
double bank_card;//size(8)
char id;//size(1)
short age;//size(2)
};//sizeof(f)=8x3=24,内存对齐
十、多继承
同时继承多个基类的属性和方法。
class Father {
public:
int height;
};
class Mother {
public:
int beauty;
};
class Son : public Father, public Mother {
};//sizeof(s)=8
不同基类有相同的属性名:
class Father {
public:
int height;
int age;
};
class Mother {
public:
int beauty;
int age;
};
class Son : public Father, public Mother {
};//sizeof(s)=16
void main() {
Son s;
s.Father::age=28;
s.Mother::age=26;
cout << s.age << endl;//报错
cout << s.Father::age << endl;//28
cout << s.Mother::age << endl;//26
};