C++中级-类的封装

类定义

#include <iostream>
#include <string>
using namespace std;


#define PI  3.141592657

class Circle {
    //访问权限
    //公共权限
public:
    //属性
    int half_r;
    //行为
    double cal() { return 2 * PI * half_r; }
};

class Studne {
public:
    string name;
    int id;
    void showUp() {
        cout << "name:" << name << endl;
        cout << "id:" << id << endl;
    };
    void setName(string myname) {
        name = myname;
    }
    void setID(int myid) {
        id = myid;
    }
};

int main() {

    //arg1
    Circle c1; //实例化
    c1.half_r = 20;
    int res = c1.cal();
    cout << res << endl;

    //arg2
    Studne s1;
    s1.setName("jack");
    s1.setID(65535);
    s1.showUp();



    return 0;
}

类的访问权限

#include <iostream>
#include <string>
using namespace std;
/*
public公共权限:类内YES,类外YES;
protected保护权限:类内YES,类外NOT;
private私有权限:类内YES,类外NOT
*/

class Person {
protected:string username;
    
private:string passwd;
    
public:
    string name;
    int age;
    void showInfo() {
        passwd = "111";
        username = "Could";
        cout << "Name:" << name << "Age:" << age <<"Passwd: "<<passwd<< endl;
    }
};
int main() { 

    Person p1;
    p1.age = 20;
    p1.name = "Ruby";
    //p1.passwd = "122";False!
    //p1.username = "ss";False!
    p1.showInfo();

    return 0; 

}

 类的属性私有化

#include <iostream>
#include <string>
using namespace std;

class Man {
//私有权限,只有内部能控制。
private:
    string name;
    int age;
    string wifeName;

public://外部不能设置值,所以通过public内部一个函数设置私有权限的值。
    void setManInfo(string mname, int mage, string wn) {
        name = mname;
        age = mage;
        wifeName = wn;
    };

    void ShowInfo() {
        cout << "He name is " << name << ",and he is  " << age << "years old,his wife is " << wifeName << endl;
    }
};



int main() { 
    Man m1;
    m1.setManInfo("mick", 33, "cat");
    m1.ShowInfo();
    

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值