c++ 类成员的访问权限priavte, protected, public

 #include <iostream>
using namespace std;
/* 类成员访问权限
* private 只能在类本身被访问
* protected 能被类本身和派生类访问
* public 能被类本身和派生类以及外部任何对方访问
*/
/* 类的构造顺序是如果有基类先构造基类后构造派生类
* 类的析构顺序是先析构派生类如果有基类再析构基类
* 一个类可以含到一个以上的构造函数, 构造函数不能为虚方法
* 一个类只能有一个析构函数,析构函数请一定声明为虚方法以备派生类继承调用
* 如果你不提供构造函数,复制构造函数,赋值构造函数,析构函数,系统会自动提供一份
* 当类内含有用new产生的对象或指针时你得自己提供以上函数
*/
class AClass{
private:
    void method_a_private(char * caller){
        cout << caller << " 基类私有成员" << endl;}
protected:
    void method_a_protected(char * caller){
        cout << caller << " 基类保护成员" << endl;}
public:
    void method_a_public(char * caller){
        cout << caller << " 基类公共成员" << endl;}

    void method_a_public_call_protected(char * caller){
        cout << caller ;
        method_a_protected(" 基类公共成员 调用");
        }
    void method_a_public_call_private(char * caller){
        cout << caller ;
        method_a_private(" 基类公共成员 调用");
        }
    AClass() {cout << this << "->基类被构造" << endl;}
    ~AClass(){cout << this << "->基类被析构" << endl;}
};

class BClass:public AClass{
private:
protected:
public:
// 基类的私有成员对派生类是不可见的,所以下面方法无法通过编译
//    void show_parent_private(char * caller){
//        cout << caller ;
//        AClass::method_a_private(" 派生类公共成员 调用");
//        }
    void show_parent_protected(char * caller){
        cout << caller ;
        AClass::method_a_protected(" 派生类公共成员 调用");
        }
    BClass() {cout << this << "->派生类被构造" << endl;}
    ~BClass(){cout << this << "->派生类被析构" << endl;}
};
int main()
{
    AClass a;
    a.method_a_public("基类对象 调用"); // 公共成员允许外部类访问
    a.method_a_public_call_protected("基类对象 调用");
    a.method_a_public_call_private("基类对象 调用");
//    a.method_a_protected("基类对象 调用"); // error 保护成员对于外部调用等效于私有成员
//    a.method_a_private("基类对象 调用"); // error 私有成员对于外部调用者不可见
    BClass b;
    b.method_a_public("派生类对象 调用"); // 外部类可以直接通过派生类访问基类的方法
//    b.method_a_protected("派生类对象 调用"); // error 外部类只能访问公共方法
//    b.method_a_private("派生类对象 调用"); // error
    b.show_parent_protected("派生类对象 调用");// 透过派生类的公共成员访问基类的保护成员
    return 0;
}
---------------------------------------------------------------------------------------------
winxp + codeblock 8.02 编译通过
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值