How to create classes and objects in C++?
In C++, classes are created using the keyword “class” and objects are created using the keyword “new”.
Here is a simple example:
#include <iostream>
// 定义一个类
class MyClass {
public:
void myFunction() {
std::cout << "Hello, this is my function!" << std::endl;
}
};
int main() {
// 创建一个对象
MyClass myObject;
// 调用对象的成员函数
myObject.myFunction();
return 0;
}
In the example above, we defined a class named MyClass, declared a member function named myFunction within it, and then created an object named myObject in the main function, calling the myFunction function of the object.
Objects can be initialized through a class’s constructor and the resources occupied by the object can be released through the class’s destructor. The class’s constructor and destructor are automatically called when the object is created and destroyed, respectively.