#include <iostream>
#include <string>
class Person {
public:
// 默认构造函数
Person() {
name = "Unknown";
age = 0;
std::cout << "Default constructor called." << std::endl;
}
// 带参数的构造函数
Person(std::string n, int a) {
name = n;
age = a;
std::cout << "Parameterized constructor called." << std::endl;
}
// 析构函数
~Person() {
std::cout << "Destructor called." << std::endl;
}
// 成员函数
void displayInfo() {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
private:
std::string name;
int age;
};
int main() {
// 使用默认构造函数创建对象
Person person1;
person1.displayInfo();
// 使用带参数的构造函数创建对象
Person person2("Alice", 30);
person2.displayInfo();
return 0;
}
Person() 是一个没有参数的构造函数,它在创建对象时自动调用。这里将 name 初始化为 "Unknown",age 初始化为 0。Person(std::string n, int a) 是一个带有参数的构造函数,允许我们在创建对象时传递初始值给成员变量 name 和 age。~Person() 是在对象销毁时自动调用的函数,通常用于释放资源。这里只是简单地输出一条消息。displayInfo() 用于显示对象的信息。main() 中演示了如何使用默认构造函数和带参数的构造函数来创建 Person 对象,并调用 displayInfo() 显示对象信息。上一篇:c++ 智能指针
下一篇:c++map
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站