[c++]public,private运用范围简述

#include<iostream>

class Object{
    public:
        int score;
        float height ;
        void Test(){
            printf("test function,age=%d\n",age);
            printf("test function,num=%d",num);
        }         
    
    private:  
        int age=10;   
        void Testprivate(){
            printf("testprivate function\n");
        }

    protected:
        int num=91;
        void Testprotected(){
            printf("testprotected function\n");
        }
 };
int main(){
    Object student1;
    student1.score=90;
    student1.height=170.1;
    student1.Test();

    //TestPrivate();        不能在此处使用
    //Testprotected();      不能在此处使用 


    return 0;
}

private定义的变量和函数只能在类内部使用;

public定义的变量和函数可以从任何地方访问

#include<iostream>
using namespace std;
class Object{
    public:
        int score;
        float height ;
        void Test_public( );
    
    private:  
        int age=10;   
    void Test_private(int score);

    protected:
        int num=91; 
        void Test_protected();        
};

 /*函数定义到class外面*/
    void Object:: Test_public(){
        printf("test function,age=%d\n",age);
        printf("test function,num=%d",num);
    }    

    void Object:: Test_private(int score){
        cout<<"score="<<score<<endl;    
    }

    void Object:: Test_protected(){
        printf("testprotected function\n");
    }

int main(){
    Object student1;
    student1.score=90;
    student1.height=170.1;
    student1.Test_public(); 
    //TestPrivate();        不能在此处使用
    //Test_protected();      不能在此处使用 
    return 0;
}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值