Person
类要求:
idCard
(身份证号)、name
(姓名)、gender
(性别)、age
(年龄)、profession
(职业)、phone
(联系方式),并定义构造函数初始化这些字段。message()
:输出个人信息。答案:
cpp
#include
#include
using namespace std;
class Person {
private:
string idCard, name, gender, profession, phone;
int age;
public:
// 构造函数初始化字段
Person(string id, string n, string g, int a, string p, string ph)
: idCard(id), name(n), gender(g), age(a), profession(p), phone(ph) {}
// 输出信息
void message() {
cout << "ID: " << idCard << "\nName: " << name << "\nGender: " << gender
<< "\nAge: " << age << "\nProfession: " << profession
<< "\nPhone: " << phone << endl;
}
};
解释:
private
,通过构造函数初始化。message()
方法:直接输出所有字段信息。要求:用类实现计算器,支持两个数的加、减、乘、除,使用多态或抽象类设计。
答案:
cpp
#include
using namespace std;
class Operation {
public:
virtual double calculate(double a, double b) = 0;
};
class Add : public Operation {
public:
double calculate(double a, double b) override { return a + b; }
};
class Subtract : public Operation {
public:
double calculate(double a, double b) override { return a - b; }
};
class Multiply : public Operation {
public:
double calculate(double a, double b) override { return a * b; }
};
class Divide : public Operation {
public:
double calculate(double a, double b) override {
if (b == 0) throw "Division by zero!";
return a / b;
}
};
int main() {
Operation* op = new Add();
cout << "5 + 3 = " << op->calculate(5, 3) << endl; // 输出 8
delete op;
}
解释:
Operation
:定义纯虚函数 calculate
,强制子类实现。replace
函数要求:模仿 basic_string::replace
,实现函数:
cpp
string& myReplace(string& str, size_t index, size_t num, const string& replacement);
答案:
cpp
#include
using namespace std;
string& myReplace(string& str, size_t index, size_t num, const string& replacement) {
if (index > str.length()) return str; // 检查索引有效性
// 删除原字符串的 [index, index+num) 部分
str.erase(index, num);
// 插入 replacement
str.insert(index, replacement);
return str;
}
解释:
index
超出范围,直接返回原字符串。erase
和 insert
:利用 string
内置方法先删除原内容,再插入新字符串。replace
类似。Person
类实现 Student
要求:
Person
,新增字段 studentId
(学号)和 scores
(成绩数组)。averageScore()
:计算平均分。答案:
cpp
class Student : public Person {
private:
string studentId;
vector<int> scores;
public:
Student(string id, string name, string gender, int age,
string profession, string phone, string sid, vector<int> sc)
: Person(id, name, gender, age, profession, phone),
studentId(sid), scores(sc) {}
double averageScore() {
if (scores.empty()) return 0;
int sum = 0;
for (int score : scores) sum += score;
return static_cast<double>(sum) / scores.size();
}
};
解释:
Student : public Person
表示公有继承。要求:将 Person
对象的信息写入文本文件 person.txt
。
答案:
cpp
#include
void writePersonToFile(const Person& p, const string& filename) {
ofstream file(filename);
if (file.is_open()) {
file << "ID: " << p.getIdCard() << "\n"
<< "Name: " << p.getName() << "\n";
// 其他字段类似...
file.close();
}
}
解释:
ofstream
使用:通过文件流对象写入文本。is_open()
确保文件正确打开。