C++ core programming classes and objects---the three major characteristics of C++ object-oriented--encapsulation

Table of contents

classes and objects

Concepts of classes and objects

Three major characteristics of C++ object-oriented

1. Encapsulation

Encapsulation case 1: Design a student class that can assign values ​​​​to names and student numbers, and can display students' names and student numbers.

2. Access rights

There are three types of access rights

The difference between struct and class

3. Privatization of member attributes

Advantages of privatizing member properties:

4. Packaging cases

Case 1: Design cube class

Case 2: The relationship between points and circles


classes and objects

Object-oriented programming (OOP) is one of the cornerstones of modern programming. C++ is a language that supports OOP and allows you to create classes and objects.

Concepts of classes and objects

  1. Class is an abstraction of objects. A class is an abstract data type. Their relationship is that objects are instances of classes, and classes are templates of objects. The object is generated through new className and is used to call the method of the class; the constructor of the class.

  2. Meaning of class:

    2-1. Classes encapsulate attributes and methods, and at the same time control access to the attributes and methods of the class.

    2-2. Classes are abstracted by us based on objective things to form a class of things, and then we use classes to define objects and form specific individuals of such things.

    2-3. A class is a data type, a class is abstract, and an object is a concrete variable that occupies memory space.

  3. Class access control

    In C++, you can define access levels for the attributes and methods of a class. Public-modified attributes and methods can be accessed inside the class or outside the class. Private properties and methods can only be accessed within the class.

  4. Behavior

    The public operations of all objects are member functions (usually used as public attributes) attributes: the public characteristics of all objects are data members (usually used as protected attributes)

Three major characteristics of C++ object-oriented

The three major features of C++ object-oriented are: encapsulation, inheritance, and polymorphism.

The purpose of encapsulation is to achieve code modularization, the purpose of inheritance is to achieve code expansion, the purpose of static polymorphism is function overloading and generic programming, and the purpose of dynamic polymorphism is virtual function rewriting.

C++ believes that everything is an object, and objects have their properties and behaviors.

For example:

People can be used as objects. Their attributes include name, age, height, weight... and their behaviors include walking, running, jumping, eating, singing...

A car can also be used as an object. Its attributes include tires, steering wheels, and lights... its behaviors include carrying people, playing music, and turning on air conditioning...

Objects with the same properties can be abstractly called classes. People belong to the human class, and cars belong to the car class.

1. Encapsulation

Encapsulation is one of the three major features of C++ object-oriented. Encapsulation is to organically combine data and behavior to form a whole. Data and data processing operations are combined to form a class, and both data and functions are members of the class.

1. The meaning of packaging:

  • Use attributes and behaviors as a whole to express things in life
  • Control attributes and behaviors with permissions

2. Grammar:

class class name {access permissions: attributes/behavior}

Example: Get the circumference of a circle through actions in a circle class

#include<iostream>

#include<string>

using namespace std;

// 圆周率

const double PI = 3.14;

// 设计一个圆类   求圆的周长

// class(一个类) 类名

// class代表设计一个类,类后面紧跟着的就是类的名称

class circle {

    // 访问权限

    // 公共权限

public:

    // 属性

    // 半径

    int r;

    //行为:一般为函数

    // 获取周长

    double calculateZC()

    {

        return 2 * PI * r;

    }

};



int main()

{

    // 通过圆类创建具体的圆(对象)

    // 实例化   ( 通过一个类  创建一个对象的过程 )

    circle c1;

    // 给圆对象 的属性进行赋值

    c1.r = 10;
    
    cout << "圆的周长:" << c1.calculateZC() << endl;

    return 0;

}

operation result:

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Encapsulation case 1: Design a student class that can assign values ​​​​to names and student numbers, and can display students' names and student numbers.

#include<iostream>

#include<string>

using namespace std;

// 设计一个学生类,属性有姓名和学号

// 可以给姓名和学号赋值,可以显示学生的姓名和学号

// 设计学生类

class student {

public:  // 公共权限



    // 类中的属性和行为  我们统一称为  成员

    // 属性  成员属性   成员变量

    // 行为  成员函数   成员方法



    // 属性

    string name;

    int id;



    // 行为

    // 显示姓名与学号

    void showstu()

    {

        cout << "姓名: " << name << "  学号: " << id << endl;

    }



    // 可以通过对象的行为给属性赋值

    void setname(string i_name)

    {

        name = i_name;

    }

    void setID(int i_id)

    {

        id=i_id;

    }

};

int main()

{

    // 创建一个具体的学生

    // 实例化对象

    class student s1;

    // 给s1属性赋值

    s1.setname("张三");

    s1.id = 01;

    s1.showstu();



    class student s2;

    // 给s2属性赋值

    s2.name = "李四";

    s2.id = 02;

    s2.showstu();



    class student s3;

    // 通过对象的行为给属性赋值

    s3.setname("王五");

    s3.setID(03);

    s3.showstu();

    return 0;

}

 

operation result:

 

2. Access rights

When designing a class, attributes and behaviors can be placed under different permissions and controlled.

There are three types of access rights

 1. Public public permissions can be accessed by both inside and outside the member class.

 2. Protected protection permissions can be accessed within the member class, but cannot be accessed outside the class (there is an inheritance relationship, a parent-child relationship)

 3. Private private permissions can be accessed within the member class, but cannot be accessed outside the class (the parent-child relationship cannot be accessed either)

Example:

#include<iostream>

using namespace std;

class person{

public:

    // 公共权限

    string name;



protected:

    // 保护权限

    string car;



private:

    // 私有权限

    int password;



public:

    void fun()

    {

        name = "张三";

        car = "BMW";

        password = 123456;

    }

    // 不管哪种形式在类内都是可以访问的

};

int main ()

{

    // 实例化具体的对象

    class person p1;

    p1.name = "李四";



    p1.car = "AMG";  // 保护权限的内容在类外是不能访问的



    p1.password = 258258; // 私有权限的内容在类外是不能访问的

    return 0;

}

 

报错显示:

 

The difference between struct and class

The only difference between struct and class in C++ is the different default access rights.

the difference:

 struct defaults to public permissions

 class defaults to private permissions

 

Example:

#include<iostream>

using namespace std;

class C1
{

    int m_A;// 默认权限   是私有

};

struct C2
{

    int m_A;// 默认权限  是公共

};

int main ()

{

    class C1 c1;

    c1.m_A=1000;

    struct C2 c2;

    c2.m_A=100;

    return 0;

}

 

The error message shows:

 

3. Privatization of member attributes

Advantages of privatizing member properties:

 1. Set all member attributes to private so that you can control read and write permissions yourself.

 2. For write permissions, the validity of data can be detected

Example:

#include<iostream>

#include<string>

using namespace std;

// 设计一个人类

class person{

    // 设计一个public 的公共接口

public:

    // 设置姓名

    void set_name(string in_name)

    {

            name = in_name;

    }

    // 获取姓名

    string get_name()

    {

        return name;

    }

    // 设置年龄

    void set_age(int in_age)

    {

        if(in_age<=0||in_age>150){

            cout<<"你输入的年龄有误!"<<endl;

            return;

        }

        age=in_age;

    }

    // 获取年龄

    int get_age()

    {

        return age;

    }

    // 设置情人,只写

    void set_lover(string in_lover)

    {

        lover = in_lover;

}

private:

    // 姓名  可读可写

    string name;



    // 年龄        可读可写

    int age = 0;



    // 情人        只写

    string lover;

};

int main()

{

    class person p1;

    p1.set_name("张三");

    cout<<"姓名为: "<<p1.person::get_name()<<endl;

    p1.set_age(200);

    cout<<"年龄为: "<<p1.person::get_age()<<endl;

    p1.set_lover("鞠婧祎");

    return 0;

}

operation result:

4. Packaging cases

Case 1: Design cube class

Design Cube Class (Cube)

Find the area and volume of the cube

Use global functions and member functions to determine whether two cubes are equal.

Example:

#include<iostream>

#include<string>

using namespace std;

/*

1.创建立方体类

2.设计属性

3.设计行为  获取立方体面积和体积

4.分别利用全局函数和成员函数  判断两个立方体是否相等

*/

// 立方体类

class Cube{

public:

    void setL(int L)

    {

        m_L=L;

    }

    int getL()

    {

        return m_L;

    }

    void setW(int W)

    {

        m_W=W;

    }

    int getW()

    {

        return m_W;

    }



    void setH(int H)

    {

        m_H=H;

    }

    int getH()

    {

        return m_H;

    }



    // 获取立方体的面积

    int calculateS()

    {

        return 2*(m_L*m_W+m_W*m_H+m_L*m_H);

    }

    // 获取立方体的体积

    int calculateV()

    {

        return m_L*m_H*m_W;

    }

   

    // 利用成员函数判断两个立方体是否相等

    bool isSameByClass(Cube &C)

    {

        if(m_L==C.getL()&&m_W==C.getW()&&m_H==C.getH()){

            return true;

        }

        return false;

    }

private:

    int m_L;// 长

    int m_W;// 宽

    int m_H;// 高

};

// 利用全局函数判断  两个立方体是否相等

bool isSame(Cube &C1,Cube &C2)

{

    if(C1.getL()==C2.getL()&&C1.getW()==C2.getW()&&C1.getH()==C2.getH()){

        return true;

    }

    return false;

}

int main()

{

    // 创建一个立方体对象

    class Cube C1;

    C1.setL(10);

    C1.setW(10);

    C1.setH(10);

    cout<<"C1的面积为:"<<C1.calculateS()<<endl;

    cout<<"C1的体积为:"<<C1.calculateV()<<endl;



    // 创建第二个立方体

    class Cube C2;

    C2.setL(10);

    C2.setW(20);

    C2.setH(10);



    // 全局函数判断

    bool ret=isSame(C1,C2);

    if(ret){

        cout<<"C1和C2是相等的"<<endl;

    }

    else{

        cout<<"C1和C2是不相等的"<<endl;

    }



    // 成员函数判断

    ret=C1.isSameByClass(C2);

    if(ret){

        cout<<"成员函数判断:C1和C2是相等的"<<endl;

    }

    else{

        cout<<"成员函数判断:C1和C2是不相等的"<<endl;

    }

    return 0;

}

operation result:

Case 2: The relationship between points and circles

Design a circle class (Circle) and a point class (Point) to calculate the relationship between points and circles.

Example:

#include<iostream>

#include<string>

#include<cmath>

using namespace std;

// 判断点和圆的关系

/*

点到圆心的距离== 半径  点在圆上

点到圆心的距离 > 半径  点在圆外

点到圆心的距离 < 半径  点在圆内

*/

class Point

{

public:

    void setX(int X)

    {

        m_X=X;

    }

    int getX()

    {

        return m_X;

    }

    void setY(int Y)

    {

        m_Y=Y;

    }

    int getY()

    {

        return m_Y;

    }

private:

    int m_X;

    int m_Y;

};

class Circle

{

public:

    // 设置半径

    void setR(int R)

    {

        m_R=R;

    }

    int getR()

    {

        return m_R;

    }

    // 设置圆心

    void setCenter(Point center)

    {

        m_Center=center;

    }

    Point getCenter()

    {

        return m_Center;

    }

private:

    int m_R;  // 半径

    class Point m_Center;

};

// 判断点和圆的关系

void isInCircle(Circle &c,Point &p)

{

    // 计算两点间距离

    int distance=pow((pow(c.getCenter().getX()-p.getX(),2))+(pow(c.getCenter().getY()-        p.getY(),2)),0.5);



    if(distance==c.getR()){

        cout<<"点在圆上"<<endl;

    }else if(distance > c.getR()){

        cout<<"点在圆外"<<endl;

    }else{

        cout<<"点在圆内"<<endl;

    }

}

int main()

{

    // 创建一个圆  和一个圆心  的对象

    Circle c;

    c.setR(10);

    Point center;

    center.setX(10);

    center.setY(0);

    c.setCenter(center);



    // 创建一个点

    Point P;

    P.setX(10);

    P.setY(9);



    // 全局函数判断点和圆的位置关系

    isInCircle(c,P);

    return 0;

}

operation result:

Guess you like

Origin blog.csdn.net/hjl011006/article/details/132915055