C++核心编程 面向对象 类和对象-封装

 

#include <iostream>
using namespace std;
//定义一个圆类 求得圆的周长
//求圆周长的公式为   2*PI*半径

const double PI = 3.14;

class Circle {
    //访问权限
    //公共访问权限
public:
    //属性
    int m_r;

    //行为   行为一般情况下为函数
    //获取圆的周长
    double caculateZC() {
        return 2 * PI*m_r;
    }

};
//只写了class 那么我们只是创建了一个类,并不能说明这个类跟实际的圆有什么关系,所以需要实际的圆

int main() {
    //通过圆类创建具体的圆(对象)
    //实例化(通过一个类,创建一个对象的过程)
    Circle c1;
    //给圆对象的属性进行赋值
    c1.m_r = 10;
    cout << "圆的周长为:" << c1.caculateZC() << endl;

    system("pause");
    return 0;
}

案例:

#include <iostream>
using namespace std;
#include <string>
//创建设计一个学生类,属性有姓名和学号,可以给姓名和学号赋值,可以显示学生姓名和学号

class Student {
    //访问权限
public:
    //学生属性
    string name;
    int id;

    void showstu(string name,int id) {
        cout << "学生姓名" << name << "学生学号" << id << endl;
    
    }

    //给姓名赋值
    void setNname(string s_name)
    {
        name = s_name;
    }


};

int main() {
        //实例化
    /*Student stu1;
    stu1.name = "健丽";
    stu1.id = 1;

    stu1.showstu(stu1.name, stu1.id);*/
    Student stu2;
    stu2.setNname("张飒");//实现方式,调用setName的函数,实参传了一个“张飒”,相当于传值到了 string s_name 形参;也就是通过行为给属性赋值
    

    system("pause");
    return 0;

}

 

 

 

 成员函数设置为私有

//成员属性可以设置为私有

//1、可以自己控制读写权限

//2、对于写可以检测数据的有效性

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

class Person {
//一般情况下  我们将成员属性设置为私有,会在类内再设置一个公有接口,来操作私有属性
public:
    void read_name(string name) {
        m_name = name;
    
    }
    string get_name() {
    
        return m_name;
    }

private:
    string m_name;
    int  m_Age;
    string m_lover;



};

int  main() {
    Person p;
    p.read_name("张三");
    cout << "姓名为:" << p.get_name << endl;

    system("pause");
    return 0;

}
原文地址:https://www.cnblogs.com/gjianli/p/15292265.html