继承的语法

继承的优点 提高代码的复用性

#include <iostream>
using namespace std;

class CPerson //基类(父类)
{
public:
	void Eat()
	{
		cout << "吃" << endl;
	}
};

class CSupream :public CPerson  //派生类(子类)
{
public:
	void Fly()
	{
		cout << "飞" << endl;;
	}
};

int main()
{
	CPerson ps1;

	CSupream ps2;
	ps2.Eat();
	ps2.Fly();

	return 0;
}

类之间是继承关系,而类中创建的对象是没有关系的。不能子类的对象对父类的成员进行修改,父类中的成员其实并不会改变。

#include <iostream>
using namespace std;

class CPerson                   //  基类(父类)
{
public:
	int m_nMoney;
public:
	CPerson()
	{
		m_nMoney = 100;
	}
};

class CSuperMan : public CPerson    //  派生类(子类)
{
public:
	int m_nMoney;
public:
	CSuperMan()
	{
		m_nMoney = 200;
	}
};

int main()
{
	CPerson ps1;
	CSuperMan ps2;
	
	ps2.CPerson::m_nMoney = 1;

	cout << ps1.m_nMoney << endl;  //100


	system("pause");
	return 0;
}
#include <iostream>
using namespace std;

class CPerson                   //  基类(父类)
{
public:
	int m_nMoney;
public:
	CPerson()
	{
		m_nMoney = 100;
	}
public:
	void Show()
	{
		cout << "CPerson::Money " << m_nMoney << endl;
	}
};
//  继承         把父类中的非static 成员继承过来
//  继承的优点? 提高复用性
class CSuperMan : public CPerson    //  派生类(子类)
{
public:
	int m_nMoney;
public:
	CSuperMan()
	{
		m_nMoney = 200;
	}
public:
	void Fly()
	{
		cout << "CSuperMan::Fly" << endl;
	}
};

int main()
{
	CSuperMan ss;
	ss.Show();
	ss.Fly();

	cout << sizeof(CSuperMan) << endl;  //8
	cout << ss.CSuperMan::m_nMoney << endl;       //  继承里 同名的成员 需要用   类名::  区分
	cout << ss.CPerson::m_nMoney << endl;


	system("pause");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值