Chapter 8: Introduction to Classes and Objects in C++

Chapter 8: Introduction to Classes and Objects in C++

In Object-Oriented Programming (OOP), classes and objects are core concepts. C++ is a language that supports object-oriented programming. Below we will introduce the concepts of classes and objects in C++ in detail, and help you better understand it through rich code examples and practical cases.

Basic concepts of classes and objects

class

In C++, a class is a user-defined data type that describes a group of objects with similar characteristics and behaviors by encapsulating data and operations on data. A class can be thought of as a template or blueprint that defines the properties (member variables) and behavior (member functions) of an object.

Here is an example of a simple class:

#include <iostream>
using namespace std;

// 定义一个点类
class Point {
    
    
public:
    // 成员变量
    int x;
    int y;

    // 成员函数
    void display() {
    
    
        cout << "x = " << x << ", y = " << y << endl;
    }
};

int main() {
    
    
    // 创建一个Point对象
    Point p1;

    p1.x = 10;
    p1.y = 20;

    p1.display();

    return 0;
}

operation result:

x = 10, y = 20

In the above code, we defined a Pointclass with two member variables xand yand one member function display(). In main()the function, we create an Pointobject of a class p1, access and modify its member variables through the object, and call member functions.

object

An object is an instantiation of a class, that is, a concrete entity created from the definition of the class. Each object has its own set of property values ​​that represent a specific instance of that class.

Taking the above point class as an example, we can create multiple point objects, and each object represents a different coordinate point.

#include <iostream>
using namespace std;

class Point {
    
    
public:
    int x;
    int y;

    void display() {
    
    
        cout << "x = " << x << ", y = " << y << endl;
    }
};

int main() {
    
    
    Point p1;
    p1.x = 10;
    p1.y = 20;
    p1.display();

    Point p2;
    p2.x = 30;
    p2.y = 40;
    p2.display();

    return 0;
}

operation result:

x = 10, y = 20
x = 30, y = 40

In the above code, we created Pointobjects of two classes p1and p2they represent different coordinate points respectively. Each object has its own independent xand yproperty values.

Constructors and Destructors

Constructor

A constructor is a special member function used for initialization when an object is created. It has the same name as the class, has no return type, and can only be called automatically at object creation time.

Here is an example showing how to define and use a constructor:

#include <iostream>
using namespace std;

class Point {
    
    
public:
    int x;
    int y;

    // 默认构造函数
    Point() {
    
    
        cout << "调用默认构造函数" << endl;
        x = 0;
        y = 0;
    }

    // 带参数的构造函数
    Point(int a, int b) {
    
    
        cout << "调用带参数的构造函数" << endl;
        x = a;
        y = b;
    }

    void display() {
    
    
        cout << "x = " << x << ", y = " << y << endl;
    }
};

int main() {
    
    
    Point p1;
    p1.display();

    Point p2(10, 20);
    p2.display();

    return 0;
}

operation result:

调用默认构造函数
x = 0, y = 0
调用带参数的构造函数
x = 10, y = 20

In the above code, we Pointhave defined two constructors for the class: one is the default constructor and the other is the constructor with parameters. The default constructor is called automatically when the object is created and is used to initialize xand yto 0. The constructor with parameters receives xthe yinitial value and is initialized when the object is created.

Destructor

Destructors are special member functions used to clean up when an object is destroyed. It has the same name as the class, preceded by a tilde ( ~), has no parameters and a return type, and is called automatically when the object is deleted.

Here is an example showing how to define and use a destructor:

#include <iostream>
using namespace std;

class Point {
    
    
public:
    int x;
    int y;

    Point() {
    
    
        cout << "调用构造函数" << endl;
        x = 0;
        y = 0;
    }

    ~Point() {
    
    
        cout << "调用析构函数" << endl;
    }

    void display() {
    
    
        cout << "x = " << x << ", y = " << y << endl;
    }
};

int main() {
    
    
    Point p1;
    p1.display();

    {
    
     // 代码块内创建的对象会在其作用域结束后自动销毁
        Point p2(10, 20);
        p2.display();
    }

    return 0;
}

operation result:

调用构造函数
x = 0, y = 0
调用构造函数
x = 10, y = 20
调用析构函数

In the above code, we Pointhave defined a destructor for the class. This destructor is called automatically when the object is destroyed and goes out of scope. In the example, the object is p2destroyed after the scope ends, so the destructor is called.

Member Access Control

In C++, class members (including variables and functions) can specify their accessibility through access control symbols. C++ provides three access control symbols: public, privateand protected.

  • public: Public members can be accessed both inside and outside the class.
  • private: Private members can only be accessed inside the class, and cannot be directly accessed outside.
  • protected: Protected members are similar to private members, but can be accessed by derived classes.

Here is an example showing the use of different access control characters:

#include <iostream>
using namespace std;

class Rectangle {
    
    
public:
    // 公有成员函数
    void setDimensions(int length, int width) {
    
    
        if (length > 0 && width > 0) {
    
    
            this->length = length;
            this->width = width;
        }
    }

    int getArea() {
    
    
        return length * width;
    }

private:
    // 私有成员变量
    int length;
    int width;
};

int main() {
    
    
    Rectangle rect;

    // 访问公有成员函数
    rect.setDimensions(5, 10);

    // 访问公有成员函数
    cout << "面积:" << rect.getArea() << endl;

    // 下面这行代码会导致编译错误,因为length和width是私有成员,无法在外部访问
    // rect.length = 2; 

    return 0;
}

operation result:

面积:50

In the above code, setDimensions()and getArea()are public member functions that can be called through the object. And lengthand widthare private member variables that cannot be accessed directly outside the class.

static member

In C++, a static member is a member of a class that belongs to the entire class rather than any object of the class. It is associated with a class, not an object. Static members are shared among all objects of the class and can be accessed directly without creating an object.

Here is an example of how to define and use static members:

#include <iostream>
using namespace std;

class Circle {
    
    
public:
    double radius;        // 普通成员变量
    static int count;     // 静态成员变量

    Circle(double r) {
    
    
        radius = r;
        count++;
    }

    void display() {
    
    
        cout << "半径:" << radius << endl;
        cout << "总数:" << count << endl;
    }

    static void showCount() {
    
    
        cout << "当前圆的数量:" << count << endl;
    }
};

int Circle::count = 0;   // 静态成员变量需要在类外进行初始化

int main() {
    
    
    Circle c1(1.5);
    Circle c2(2.5);

    c1.display();      // 访问普通成员变量和函数
    c2.display();

    Circle::showCount();   // 直接通过类名访问静态成员函数

    return 0;
}

operation result:

半径:1.5
总数:2
半径:2.5
总数:2
当前圆的数量:2

In the above code, we define a Circleclass that contains a normal member variable radiusand a static member variable count. In the constructor, counta value that is incremented each time the object is created. At the same time, we also define an ordinary member function display()to display the radius of the circle and the current countvalue, and a static member function showCount()to directly display the number of the current circle.

It can be seen from the running results that although we only created two Circleobjects, countthe value of is shared and showCount()can be directly accessed through static member functions.

class friend

In C++, you can use the friend keyword to declare that a function or class is a friend of another class. A friend function or class can access private members of the class that declares it a friend.

Here is an example showing how to use class friends:

#include <iostream>
using namespace std;

class Rectangle {
    
    
private:
    int length;
    int width;

public:
    Rectangle(int l, int w) {
    
    
        length = l;
        width = w;
    }

    // 声明友元函数
    friend int getArea(Rectangle r);
};

// 定义友元函数,可以访问Rectangle类的私有成员
int getArea(Rectangle r) {
    
    
    return r.length * r.width;
}

int main() {
    
    
    Rectangle rect(5, 10);
    cout << "面积:" << getArea(rect) << endl;

    return 0;
}

operation result:

面积:50

In the above code, we defined a Rectangleclass with two private member variables lengthand width. Then we declare a friend function getArea()that can directly access Rectanglethe private members of the class. In main()the function, we create an Rectangleobject rectand calculate its area through a friend function.

inherit

Inheritance is an important concept in object-oriented programming, which allows us to create a new class (derived class/child class) that inherits properties and behaviors from an existing class (base class/parent class). A derived class can inherit public, protected, and private members from a base class.

Here is an example showing how to use inheritance:

#include <iostream>
using namespace std;

// 基类
class Shape {
    
    
protected:
    int width;
    int height;

public:
    void setDimensions(int w, int h) {
    
    
        width = w;
        height = h;
    }
};

// 派生类
class Rectangle : public Shape {
    
    
public:
    int getArea() {
    
    
        return width * height;
    }
};

int main() {
    
    
    Rectangle rect;
    rect.setDimensions(5, 10);
    cout << "矩形的面积:" << rect.getArea() << endl;

    return 0;
}

operation result:

矩形的面积:50

In the above code, we have a base class Shapeand a derived class Rectangle. RectangleClasses inherit Shapeclass widthand heightmember variables, and setDimensions()functions. In main()the function, we create an Rectangleobject and setDimensions()set its size by calling a member function of the base class. Then, we getArea()calculate the area of ​​the rectangle through a member function of the derived class.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/132241411