Home > Article > Backend Development > Usage of class in c++
Class is a blueprint in C that encapsulates data and functionality. Its members include: Data members: variables that store data. Method: A function that defines a class operation or behavior. Object: An instance created from a class that has all the data members and methods in the class.
Usage of class in C
What is class?
Class is a blueprint in C that encapsulates data and functionality. It allows the creation of object instances with specific properties and methods.
Class syntax:
<code class="cpp">class class_name { // 类的数据成员(变量) data_member1; data_member2; // 类的方法(函数) method1(); method2(); };</code>
Members of the class:
Data members: Data stored in the class variable.
Method: Function of the operation or behavior defined in the class.
Object of class:
Instance created from class. The object has all the data members and methods defined in the class.
Constructor of class:
Special method called when creating an object, used to initialize the data members of the object.
Destructor of class:
Special method called when the object is destroyed to release occupied resources.
Class access control:
Controls the visibility of class members to external code. There are three access control levels:
Class usage example:
<code class="cpp">class Person { public: string name; // 数据成员 void greet() { // 方法 cout << "Hello, my name is " << name << endl; } }; int main() { Person john; // 创建对象 john john.name = "John Doe"; // 访问数据成员 john.greet(); // 调用方法 return 0; }</code>
The above is the detailed content of Usage of class in c++. For more information, please follow other related articles on the PHP Chinese website!