c++ 基础知识-类和对象-继承 1
1.基本语法
#include <iostream>
#include <string>
using namespace std;
//继承
// 基类 父类 包含一些公共或者说可以重复利用的内容
class Base
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
//公共继承 public
class A:public Base
{
public:
//构造函数
A(int i);
};
//构造函数
A::A(int i)
{
m_A = i;
}
void fun()
{
A a(89);
cout<<a.m_A<<endl;
}
int main()
{
fun();
return 0;
}
2.继承方式
三种继承均不可以访问私有
public 公共继承 继承
protected 保护继承
private 私有继承
#include <iostream>
#include <string>
using namespace std;
//继承
// 基类 父类 包含一些公共或者说可以重复利用的内容
class Base
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
//公共继承 public
class A:public Base
{
public:
//构造函数
A(int i);
};
//构造函数
A::A(int i)
{
m_A = i;
//m_B = i;//error C2248: “Base::m_B”: 无法访问 protected 成员(在“Base”类中声明)
//m_C = i;//error C2248: “Base::m_C”: 无法访问 private 成员(在“Base”类中声明)
}
//保护继承 protected
class B:protected Base
{
public:
//构造函数
B(int i);
};
//构造函数
B::B(int i)
{
m_A = i;//“Base::m_A”不可访问,因为“B”使用“protected”从“Base”继承
m_B = i;
//m_C = i;//“Base::m_C”: 无法访问 private 成员(在“Base”类中声明)
}
void fun_A()
{
A a(89);
cout<<a.m_A<<endl;
//cout<<a.m_B<<endl;
//cout<<a.m_C<<endl;
}
void fun_B()
{
B b(888);
//cout<<b.m_A<<endl;//error C2247: “Base::m_A”不可访问,因为“B”使用“protected”从“Base”继承
//cout<<b.m_B<<endl;//error C2247: “Base::m_A”不可访问,因为“B”使用“protected”从“Base”继承
//cout<<b.m_C<<endl;//error C2247: “Base::m_A”不可访问,因为“B”使用“protected”从“Base”继承
}
int main()
{
fun_B();
return 0;
}
3.继承中的对象模型
#include <iostream>
#include <string>
using namespace std;
//继承
// 基类 父类 包含一些公共或者说可以重复利用的内容
class Base
{
public:
int m_A;
protected:
int m_B;
private:
int m_C;
};
//公共继承 public
class A:public Base
{
public:
int m_D;
};
void fun_A()
{
A a;
//父类中所有的成员均被子类继承
cout<<"size of son = "<<sizeof(a)<<endl;
//输出size of son = 16
}
int main()
{
fun_A();
return 0;
}