C++基础 —— (29)编译时的访问权限控制
»
    C++中有访问权限修饰符:public、protected和private。它们限定了一个类之外的函数能够访问一个类的哪些数据。

    这里要指出的是,这些访问权限修饰符仅在编译阶段起效果,在运行阶段,当一个外部函数访问一个private的成员变量的内存地址时,C++程序不会去判断和校验这个内存地址的访问权限。这减少了大量的内存访问权限判断,所以,C++是接近C的高效的开发语言。

    当然,也就是,在C++中,程序可以通过内存地址的偏移来读写private的成员变量。

     看下列例子代码:
#include <iostream>
class AccessControlExample{
public:
    int publicA=11223344;
    int publicB=55667788;
private:
    int privateC=99001122;
};
void printA(int* firstAddressP){
    std::cout<<*firstAddressP<<endl;
}
void printB(int* firstAddressP){
    std::cout<<*(firstAddressP+1)<<endl;
}
void printC(int* firstAddressP){
    std::cout<<*(firstAddressP+2)<<endl;
}
void changeA(int* firstAddressP){
    *firstAddressP=1234;
}
void changeB(int* firstAddressP){
    *(firstAddressP+1)=5678;
}
void changeC(int* firstAddressP){
    *(firstAddressP+2)=9012;
}

int main(){
    AccessControlExample ace;
    printA(&(ace.publicA));
    printB(&(ace.publicA));
    printC(&(ace.publicA));//外部函数访问private变量
    changeA(&(ace.publicA));
    changeB(&(ace.publicA));
    changeC(&(ace.publicA));//外部函数修改private变量
    printA(&(ace.publicA));
    printB(&(ace.publicA));
    printC(&(ace.publicA));
}

输出结果为:
11223344
55667788
99001122//外部函数访问结果
1234
5678
9012//外部函数修改结果
            
«
——张人杰·www.v-signon.com学习者共勉
返回上一页
备案号:京ICP备19038994号-2
个人作品网站:www.up-task.com 主办:个人 English
网站内容如有侵权,请联系删除:1307776259@qq.com