C++类总结

参考:

C++中的private, public, protected_c++ private-CSDN博客
https://www.cnblogs.com/corineru/p/11001242.html

C++ 中 Private、Public 和 Protected 的区别

Private

Public

Protected

声明为private类成员只能由基类内部的函数访问。

可以从任何地方访问声明为public的类成员。

声明为protected类成员可以在基类及其派生类中访问。

private成员使用关键字private后跟冒号 (:) 字符来声明。

public成员使用关键字public后跟冒号 (:) 字符来声明。

protected成员使用关键字protected后跟冒号 (:) 字符来声明。

private成员能被子类继承,但不能被子类的对象直接访问。

public成员可以在子类中被继承并被直接访问。

protected成员可以在子类中被继承并访问。

它为其数据成员提供高安全性。

它不为其数据提供任何类型的安全性。

它提供的安全性低于private访问说明符。

可以在友元功能的帮助下访问private成员。

public成员可以在有或没有友元功能的帮助下访问。

protected成员不能通过友元函数访问,它们在类之外是不可访问的,但它们可以被该类的任何子类(派生类),包括派生类及派生类的子类访问。

继承方式总结:


class Base {
  public:
    int x;
  protected:
    int y;
  private:
    int z;
    
};
 
class PublicDerived: public Base {
  // x is public and is accessible in PublicDerived class
  // y is protected and is accessible in PublicDerived class
  // z is not accessible from PublicDerived, as it is a private member of the base class
    
};
 
class ProtectedDerived: protected Base {
  // x is protected and is accessible in ProtectedDerived class
  // y is protected and is accessible in ProtectedDerived class
  // z is not accessible from ProtectedDerived, as it is a private member of the base class
    
};
 
class PrivateDerived: private Base {
  // x is private and is only accessible by the member functions of the PrivateDerived class
  // y is private and is only accessible by the member functions of the PrivateDerived class
  // z is not accessible from PrivateDerived, as it is a private member of the base class
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liuzl_2010

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值