C++:类继承 private, protected的区别

来源:互联网 发布:中国青少年肥胖率数据 编辑:程序博客网 时间:2024/05/16 12:04

先看实例:

#include <iostream>class Mammal{public:    // constructors    Mammal():itsAge(2), itsWeight(5){}    ~Mammal(){}protected:    int itsAge;    int itsWeight;};class Dog: public Mammal{public    // constructors    Dog():itsBreed(1){}    ~Dog(){}    // Other methods    void WagTail(){        std::cout<<"Tail wagging...\n";        std::cout<<itsAge<<std:endl;    }private:    int itsBreed;}int main(){    Dog fido;    fido.WagTail();    return 0;}

在WagTail()函数中,我们直接访问了protected变量itsAge
假如我们在定义Mammal类时,将itsAge设置为private时,在WagTail中引用itsAge,程序将报错
这个例子说明:
protected的数据成员和函数对派生的类是完全可见的,而private,对派生类是不可见的。其他方面与private一样。

备注:以下结论没有经过验证,记录在此,仅供自己理解

以Linux的文件权限的概念来说明:由于没有x概念,因此只涉及r, w概念假如:hello.cpp文件为例publicrw(owner)|rw(group)|rw(others)protected:  rw|rw|--private:    rw|--|--因此,当itsAge, itsWeight为protected时,WagTail()函数可以访问itsAge, itsWeight;当itsAge, itsWeight为private时, WagTail()函数不可以访问;而不论itsAge, itsWeight是protected还是private, main()函数都不可以访问itsAge,itsWeight,itsBreed;即fido.itsAge // error fido.itsWeight // error fido.itsBreed //error如果需要访问必须通过public的成员函数或变量, 比如fido.WagTail()这类函数
1 0
原创粉丝点击