Classes and Objects in C + +

  • Share this:
post-title
C + + is a widely used programming language that supports object-oriented programming (OOP). In C + +, a class is a blueprint for an object, defining its properties and methods. By creating instances of classes, we can create objects that can have properties and methods defined by the class. The core idea of object-oriented programming is to encapsulate data and the method of manipulating data, making the code more modular, reusable and easy to maintain. For example, we can represent a student with a simple class: ```cpp class Student { public: //Attributes string name; int age; //Constructor Student(string n, int a) : name(n), age(a) {} //method void setName(string n) { name = n; } void setAge(int a) { age = a; } string getName() const { return name; } int getAge() const { return age; } }; ``` In this example, `Student` is a class with two properties (`name` and `age`) and a constructor. We also define some methods (`setName`, `setAge`, `getName` and `getAge`) for setting and getting the value of the property.

Classes and objects in C + +, object-oriented programming instances.

In modern software development, object-oriented programming (OOP) has become an important programming paradigm.

By encapsulating data and methods of manipulating data, object-oriented programming improves the maintainability, reusability, and scalability of code.

C + + as a language that supports object-oriented programming, its core concepts include classes and objects.

This article will introduce classes and objects in C + + through a practical application scenario, and show how to use object-oriented programming to solve real-world problems.

1. Definition and basic usage of classes.

In C + +, a class is a user-defined type that describes a collection of objects with the same properties and behavior.

A class consists of data members (member variables) and member functions (member methods).

Data members are used to store the state of an object, while member functions define the operations that an object can perform.

Example: Define a simple PersonClass.


#include 
#include 

// 定义Person类
class Person {
private:
    std::string name; // 姓名
    int age;          // 年龄

public:
    // 构造函数
    Person(std::string n, int a) : name(n), age(a) {}

    // 获取姓名
    std::string getName() const {
        return name;
    }

    // 设置姓名
    void setName(std::string n) {
        name = n;
    }

    // 获取年龄
    int getAge() const {
        return age;
    }

    // 设置年龄
    void setAge(int a) {
        age = a;
    }

    // 打印个人信息
    void printInfo() const {
        std::cout << "Name: " << name << ", Age: " << age << std::endl;
    }
};

int main() {
    // 创建Person对象
    Person person("Alice", 30);

    // 打印个人信息
    person.printInfo();

    // 修改个人信息
    person.setName("Bob");
    person.setAge(25);

    // 再次打印个人信息
    person.printInfo();

    return 0;
}

In the above example, we define a PersonClass, containing two private data members nameSumage, and the corresponding public member functions for accessing and modifying these data members.

By creating PersonClass instances, we can easily manage and manipulate personal information.

2. Inheritance and polymorphism.

Inheritance is an important feature of object-oriented programming, which allows one class (derived class) to inherit the properties and behavior of another class (base class).

Through inheritance, code can be reused and expanded.

Inheritance in C + + can be public inheritance (public), protected inheritance (protected) or private inheritance (private).

Polymorphism means that the same function can perform different operations based on different inputs.

In C + +, polymorphism is usually achieved through virtual functions.

When the pointer or reference of the base class points to the object of the derived class, calling the virtual function will call the corresponding function implementation according to the actual object type.

Example: Define a base class AnimalAnd its derivatives DogSumCat


#include 
#include 

// 定义Animal基类
class Animal {
protected:
    std::string name;

public:
    Animal(std::string n) : name(n) {}

    // 纯虚函数,使Animal成为抽象类
    virtual void makeSound() const = 0;

    void printInfo() const {
        std::cout << "Name: " << name << std::endl;
    }
};

// 定义Dog派生类
class Dog : public Animal {
public:
    Dog(std::string n) : Animal(n) {}

    void makeSound() const override {
        std::cout << name << " says Woof!" << std::endl;
    }
};

// 定义Cat派生类
class Cat : public Animal {
public:
    Cat(std::string n) : Animal(n) {}

    void makeSound() const override {
        std::cout << name << " says Meow!" << std::endl;
    }
};

int main() {
    // 创建Dog和Cat对象
    Dog dog("Buddy");
    Cat cat("Whiskers");

    // 使用基类指针指向派生类对象
    Animal* animals[] = { &dog, &cat };

    // 遍历数组并调用makeSound函数
    for (Animal* animal : animals) {
        animal->printInfo();
        animal->makeSound();
    }

    return 0;
}

In this example, we define an abstract base class Animal, which contains a purely virtual function makeSound

Then, we define two derived classes DogSumCat, respectively realized makeSoundFunction.

By using the base class pointer to point to the derived class object, we can implement polymorphism, that is, call the corresponding function implementation according to the actual object type.

3. Practical application case: library management system.

In order to better understand the practical application of object-oriented programming, we will use a simple library management system to show how to use classes and objects in C + + to solve real-world problems.

This system will contain the following main functions: - Add books -Show all books - Find books - delete books

Step 1: Define BookClass.

First, we need to define a BookClass to represent books.

Each book has attributes such as title, author, ISBN number, and year of publication.


#include 
#include 
#include 
#include 

// 定义Book类
class Book {
private:
    std::string title;      // 书名
    std::string author;     // 作者
    std::string isbn;       // ISBN号
    int publishYear;        // 出版年份

public:
    Book(std::string t, std::string a, std::string i, int y) 
        : title(t), author(a), isbn(i), publishYear(y) {}

    // 获取书名
    std::string getTitle() const {
        return title;
    }

    // 设置书名
    void setTitle(std::string t) {
        title = t;
    }

    // 获取作者
    std::string getAuthor() const {
        return author;
    }

    // 设置作者
    void setAuthor(std::string a) {
        author = a;
    }

    // 获取ISBN号
    std::string getIsbn() const {
        return isbn;
    }

    // 设置ISBN号
    void setIsbn(std::string i) {
        isbn = i;
    }

    // 获取出版年份
    int getPublishYear() const {
        return publishYear;
    }

    // 设置出版年份
    void setPublishYear(int y) {
        publishYear = y;
    }

    // 打印书籍信息
    void printInfo() const {
        std::cout << "Title: " << title << ", Author: " << author 
                  << ", ISBN: " << isbn << ", Publish Year: " << publishYear << std::endl;
    }
};

Step 2: Define LibraryClass management book collection.

Next, we need to define a LibraryClass to manage a set of books.

LibraryClass will contain a std::vectorTo store all books and provide the ability to add, display, find and delete books.


// 定义Library类
class Library {
private:
    std::vector books; // 存储所有书籍的集合

public:
    // 添加书籍到图书馆
    void addBook(const Book& book) {
        books.push_back(book);
    }

    // 显示所有书籍信息
    void displayBooks() const {
        if (books.empty()) {
            std::cout << "No books in the library." << std::endl;
            return;
        }
        for (const auto& book : books) {
            book.printInfo();
        }
    }

    // 根据ISBN查找书籍并返回其在集合中的索引,如果未找到则返回-1
    int findBookByIsbn(const std::string& isbn) const {
        for (size_t i = 0; i < books.size(); ++i) {
            if (books[i].getIsbn() == isbn) {
                return static_cast(i); // 返回索引值转换为int类型
            }
        }
        return -1; // 未找到返回-1
}