继承,可以让子类拥有父类的所有成员(变量\函数)
Java:所有的Java对象最终都继承自java.lang.Object这个类
ObjC:所有的OC对象最终都继承自NSObject这个类
注意:C++中没有像Java、Objective-C的基类
// 父类
struct Person {
int m_age;
void run() {
cout << "run()" << endl;
}
};
// 子类
struct Student : Person {
int m_score;
void study() {
cout << "study()" << endl;
}
};
// 子类
struct Worker : Person {
int m_salary;
void work() {
cout << "work()" << endl;
}
};
使用示例:
Student student;
student.m_age = 18;
student.m_score = 100;
student.run();
student.study()
继承链可以很长
// 父类
struct Person {
int m_age;
};
// 子类
struct Student : Person {
int m_no;
};
// 子类的子类
struct GoodStudent : Student {
int m_money;
};
对象的内存布局
int main() {
// 12
GoodStudent gs;
// 父类的成员变量在前,子类的成员变量在后
gs.m_age = 20;
gs.m_no = 1;
gs.m_money = 2000;
// &gs == &gs.m_age
cout << &gs << endl;
cout << &gs.m_age << endl;
cout << &gs.m_no << endl;
cout << &gs.m_money << endl;
// 4
Person person;
// 8
Student stu;
cout << sizeof(Person) << endl; // 4字节
cout << sizeof(Student) << endl;// 8字节
cout << sizeof(GoodStudent) << endl; // 12字节
getchar();
return 0;
}