Home > Article > Backend Development > Embodiment of object-oriented design principles in C++
C embodies OOP principles, including: Encapsulation: Use classes to encapsulate data and methods in objects. Inheritance: Allows derived classes to inherit data and behavior from base classes. Polymorphism: allows the behavior of an object to change depending on its type, implemented through virtual functions.
The embodiment of object-oriented design principles in C
Object-oriented design (OOP) is a set of methods to achieve loose coupling, Code reuse and data encapsulation are the goals. C is an object-oriented programming language that adopts several key OOP principles.
Encapsulation
Encapsulation refers to encapsulating data and methods of operating data in objects. In C, encapsulation can be achieved using classes. For example:
class Person { private: string name; int age; public: Person(string name, int age) : name(name), age(age) {} string getName() { return name; } int getAge() { return age; } };
Inheritance
Inheritance allows one class (derived class) to inherit data and behavior from another class (base class). In C, use the public
, protected
, and private
access modifiers to control derived class access to base class members. For example:
class Student : public Person { private: string major; public: Student(string name, int age, string major) : Person(name, age), major(major) {} string getMajor() { return major; } };
Polymorphism
Polymorphism means that the behavior of an object can change depending on its type. In C, polymorphism can be achieved using virtual functions. For example:
class Animal { public: virtual string makeSound() { return "Unknown"; } }; class Dog : public Animal { public: virtual string makeSound() { return "Woof"; } }; class Cat : public Animal { public: virtual string makeSound() { return "Meow"; } }; // 实战案例 int main() { Animal* animals[] = { new Dog(), new Cat() }; for (Animal* animal : animals) { cout << animal->makeSound() << endl; } return 0; }
In this example, the Animal
class is a base class that defines the makeSound()
virtual function. The Dog
and Cat
classes are derived classes derived from the Animal
class and they override the makeSound()
method. The main function creates an Animal
array containing pointers to Dog
and Cat
objects. It then iterates through the array and calls each object's makeSound()
method. This will print different sounds depending on the type of object.
The above is the detailed content of Embodiment of object-oriented design principles in C++. For more information, please follow other related articles on the PHP Chinese website!