面试题答案
一键面试#include <iostream>
#include <string>
class Student {
private:
std::string name;
int age;
public:
// 默认构造函数
Student() : name(""), age(0) {}
// 带参数的构造函数
Student(const std::string& n, int a) : name(n), age(a) {}
// 输出学生信息的函数
void printInfo() const {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
};
int main() {
// 使用默认构造函数创建对象
Student s1;
// 使用带参数的构造函数创建对象
Student s2("Alice", 20);
// 输出两个学生对象的信息
s1.printInfo();
s2.printInfo();
return 0;
}
上述代码中:
- 定义了
Student
类,包含name
和age
成员变量。 - 实现了默认构造函数,将
name
初始化为空字符串,age
初始化为0。 - 实现了带参数的构造函数,用于同时初始化
name
和age
。 - 在
main
函数中创建了两个Student
对象,一个使用默认构造函数,另一个使用带参数的构造函数,并调用printInfo
函数输出他们的信息。