C++ 中基类及派生类中继承成员访问权限

#include <iostream>
  #include <string>
  using namespace std;
   
  class CBase {
  string name;
  int age;
  public:
  string getName() {
  return name;
  }
  int getAge() {
  return age;
  }
  protected:
  void setName(string s) {
  name = s;
  }
  void setAge(int i) {
  age = i;
  }
  };
   
  class CPublicDerive : public CBase { //用 public 指定公有继承
  public:
  void setBase(string s, int i) {
  setName(s); //调用基类的保护成员
  setAge(i); //调用基类的保护成员
  //调用基类的私有成员
  //cout << name << " " << age << endl; //编译出错
  }
  };
   
  class CProtectDerive : protected CBase { //用 protected 指定保护继承
  public:
  void setBase(string s, int i) {
  setName(s); //调用基类的保护成员
  setAge(i); //调用基类的保护成员
  //调用基类的私有成员
  //cout << name << " " << age << endl; //编译出错
  }
  string getBaseName() {
  return getName(); //调用基类的公有成员
  }
  int getBaseAge() {
  return getAge(); //调用基类的公有成员
  }
  };
   
  class CPrivateDerive : private CBase { //用 private 指定私有继承,private可以省略
  public:
  void setBase(string s, int i) {
  setName(s); //调用基类的保护成员
  setAge(i); //调用基类的保护成员
  //调用基类的私有成员
  //cout << name << " " << age << endl; //编译出错
  }
  string getBaseName() {
  return getName(); //调用基类的公有成员
  }
  int getBaseAge() {
  return getAge(); //调用基类的公有成员
  }
  };
   
  int main ( )
  {
  // 公有继承
  CPublicDerive cpublic;
  cpublic.setBase("public", 1);
  //调用基类的私有成员
  //cout << cpublic.name << " " << cpublic.age << endl; //编译出错
  //调用基类的公有成员
  cout << cpublic.getName() << " " << cpublic.getAge() << endl;
  //调用基类的保护成员
  //cpublic.setName("xyz"); //编译出错
  //cpublic.setAge(20); //编译出错
   
  // 保护继承
  CProtectDerive cprotect;
  cprotect.setBase("protect", 2);
  //调用基类的公有成员
  //cout << cprotect.getName() << " " << cprotect.getAge() << endl; //编译出错
  cout << cprotect.getBaseName() << " " << cprotect.getBaseAge() << endl;
  //调用基类的保护成员
  //cprotect.setName("xyz"); //编译出错
  //cprotect.setAge(20); //编译出错
   
   
  // 私有继承
  CPrivateDerive cprivate;
  cprivate.setBase("private", 3);
  //调用基类的公有成员
  //cout << cprivate.getName() << " " << cprivate.getAge() << endl; //编译出错
  cout << cprivate.getBaseName() << " " << cprivate.getBaseAge() << endl;
  //调用基类的保护成员
  //cprivate.setName("xyz"); //编译出错
  //cprivate.setAge(20); //编译出错
   
  // 隐式类型转换
  CBase &cbase = cpublic;
  // cbase.setName("xyz"); //编译出错
  // cbase.setAge(20); //编译出错
  cout << cbase.getName() << " " << cbase.getAge() << endl;
  return 0;
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值