c++ 基础知识-类和对象-继承1

本文详细介绍了C++中类和对象的继承概念,包括公共继承、保护继承和私有继承的区别,以及在不同继承方式下访问基类成员的权限。通过实例展示了如何创建子类并访问基类的公开和受保护成员,强调了继承时的权限控制和对象模型的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值