If you want to use a class instead of a structure, you can declare its member variables and methods in the class definition instead of the structure's data members and functions. For example, the following code demonstrates how to use a class instead of a simple struct:
class Person {
public:
// 构造函数
Person(std::string n, int a) : name(n), age(a) {}
// 成员变量
std::string name;
int age;
// 成员方法
void say_hello() {
std::cout << "Hello, my name is " << name << " and I am " << age << " years old." << std::endl;
}
};
int main() {
// 创建 Person 对象
Person person("John", 30);
// 访问成员变量
std::cout << "Name: " << person.name << std::endl;
std::cout << "Age: " << person.age << std::endl;
// 调用成员方法
person.say_hello();
return 0;
}
In the example above, we used the class Person instead of a simple structure. The constructor, member variable, and member method in the class definition correspond to the initializer, data member, and function of the structure, respectively. The advantage of using classes is that they allow you to encapsulate data and behavior and protect your code through access control.