How to utilize classes in C++?
To use classes in C++, the following steps need to be taken:
- category
class MyClass {
public:
// 成员变量
int myVar;
// 成员函数
void myFunction();
};
- Class name::function name
void MyClass::myFunction() {
// 函数的实现代码
}
- class name object name
MyClass obj;
- Can you please explain why you arrived late?
Why did you come late?
obj.myVar = 42; // 访问成员变量
obj.myFunction(); // 调用成员函数
The complete example code is as follows:
#include <iostream>
class MyClass {
public:
int myVar;
void myFunction() {
std::cout << "Hello, World!" << std::endl;
}
};
int main() {
MyClass obj;
obj.myVar = 42;
obj.myFunction();
return 0;
}
This is a simple example of using a class that you can extend and modify the member variables and member functions according to your needs.