• 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;
    }
  • 相关阅读:
    461. Hamming Distance
    Myeclipse中WebServlet cannot be resolved to a type报错
    注解方式配置Servlet(Servlet3.0)
    Oracle连接池操作
    最短路径算法
    编写学生类Stu
    编写程序,统计某旅馆住宿客人的总数,要求输入客人姓名,输出客人编号(按先后顺序自动生成),姓名以及总人数。
    货物管理系统
    c# 利用动态库DllImport("kernel32")读写ini文件(提供Dmo下载)
    shut
  • 原文地址:https://www.cnblogs.com/cou1d/p/14255058.html
Copyright © 2020-2023  润新知