C++继承

公共继承例子

#include<iostream>
using namespace std;
//公共继承
class Base {
public:
	int m_A;
protected:	//保护和私有的属性和行为(函数)只能类内访问
	int m_B;
private:
	int m_C;
};

class Son1:public Base{

};
void test01() {
	Son1 s1;
	s1.m_A = 100;	//可访问 public权限
	cout<<s1.m_A<<endl;
}
int main() {
	test01();
	system("pause");
	return 0;
}

输出结果:
在这里插入图片描述
例子

#include<iostream>
using namespace std;

class Base {
public:
	int m_A;
protected:
	int m_B;
private:
	int m_C;
};

class Son1 :public Base {
public:
	void func() {
		m_A = 10; //父类中的公共权限成员 到子类中依然是公共权限
		m_B = 10; //父类中的保护权限成员 到子类中依然是保护权限
		//m_C = 10;	//父类中的私有权限成员 子类访问不到
	}
};
void test01() {
	Son1 s1;
	s1.m_A = 100;
	//s1.m_B = 100; //到Son1中 m_B是保护权限 类外访问不到
}
int main() {

	system("pause");
	return 0;
}

保护继承例子

#include <iostream>
using namespace std;

class Base {
public:
	int m_A;
protected:
	int m_B;
private:
	int m_C;
};

//保护继承,使得父类中的可访问成员全变成保护权限
class Son2 :protected Base {
public:
	void fun() {
		m_A = 100;  //父类中公共成员,到子类中变为保护权限
		m_B = 100;  //父类中保护成员,到子类中变为保护权限
		//m_C = 100; //父类中私有成员  子类访问不到
	}
};
void test02() {
	Son2 s2;
	//s1.m_A = 1000; //在Son2中 m_A变为保护权限 ,因此类外访问不到
	//s1.m_B = 1000; //在Son2中 m_B保护权限 不可以访问

}
int main() {

	system("pause");
	return 0;
}


例子

#include <iostream>
 
using namespace std;
 
// 基类
class Shape 
{
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }
   protected:
      int width;
      int height;
};
 
// 派生类
class Rectangle: public Shape
{
   public:
      int getArea()
      { 
         return (width * height); 
      }
};
 
int main(void)
{
   Rectangle Rect;
 
   Rect.setWidth(5);
   Rect.setHeight(7);
 
   // 输出对象的面积
   cout << "Total area: " << Rect.getArea() << endl;
 
   return 0;
}

输出结果

Total area: 35

参考链接:
https://www.runoob.com/cplusplus/cpp-inheritance.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值