#include<iostream>
using namespace std;
//继承中的对象模型
class Base {
public:
int m_a;
protected:
int m_b;
private:
int m_c;
};
class Son :public Base {
public:
int m_d;
};
void test01() {
//结果16
//父类中所有非静态成员属性都会被子类继承下去
//私有属性虽然无法访问,但仍然继承了
cout << "size of Son = " << sizeof(Son) << endl;
}
int main() {
test01();
return 0;
}
构造和析构顺序
#include<iostream>
using namespace std;
//继承中的构造与析构函数
class Base {
public:
Base() {
cout << "这是Base构造函数" << endl;
}
~Base() {
cout << "这是Base析构函数" << endl;
}
};
class Son :public Base {
public:
Son() {
cout << "这是Son构造函数" << endl;
}
~Son() {
cout << "这是Son析构函数" << endl;
}
};
void test01() {
//Base b;
//继承中的构造顺序,先构造父类,再构造子类。析构时顺序相反
Son s;
}
int main() {
test01();
return 0;
}
同名成员处理
#include<iostream>
using namespace std;
class Base {
public:
Base() {
m_a = 100;
}
void func() {
cout << "this is Base func" << endl;
}
void func(int a) {
cout << "this is Base func(int)" << endl;
};
int m_a;
};
class Son :public Base {
public:
int m_a;
Son() {
m_a = 200;
}
void func() {
cout << "this is Son func" << endl;
}
};
void test01() {
Son s;
cout << "Son的m_a = " << s.m_a << endl;
//如果通过子类对象访问父类中的同名成员需要加一个作用域
cout << "Base的m_a = " << s.Base::m_a << endl;
}
void test02() {
Son s;
//若要访问父类的同名成员函数也能加作用域
s.Base::func(100);
//如果子类中存在同名成员函数,则父类同名全被隐藏,只能通过作用域访问
}
int main() {
test01();
test02();
return 0;
}