Home  >  Article  >  Backend Development  >  Usage of class in c++

Usage of class in c++

下次还敢
下次还敢Original
2024-05-09 04:09:18232browse

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++

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:

  • #public: can be accessed within the class and outside the class.
  • protected: Can be accessed within the class, derived classes and friend classes.
  • private: Can only be accessed within the class.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn