R6-1 写出派生类构造方法(C++) 分数 10 全屏浏览题目 切换布局 作者 周强 单位 青岛大学 裁判测试程序样例中展示的是一段定义基类People、派生类Student以及测试两个类的相关C++代码,其中缺失了部分代码,请补充完整,以保证测试程序正常运行。 函数接口定义: 提示: 观察类的定义和main方法中的测试代码,补全缺失的代码。 裁判测试程序样例: 注意:真正的测试程序中使用的数据可能与样例测试程序中不同,但仅按照样例中的格式调用相关函数。 #include <iostream>
时间: 2024-04-04 18:29:54 浏览: 475
class People{
protected:
char *name;
int age;
public:
People(char *n, int a){
name = new char[strlen(n)+1];
strcpy(name, n);
age = a;
}
~People(){
delete []name;
}
};
class Student: public People{
private:
float score;
public:
// 请在此处补充派生类构造方法
Student(char *n, int a, float s): People(n, a){
score = s;
}
~Student(){}
};
int main(){
Student stu("Tom", 16, 90.5);
return 0;
}
相关问题
6-2 写出派生类构造方法(C++) 分数 5  全屏浏览 作者 周强 单位 青岛大学 裁判测试程序样例中展示的是一段定义基类People、派生类Student以及测试两个类的相关C++代码,其中缺
在C++中,如果你有一个基类`People`,并想要创建一个派生类`Student`,派生类的构造方法通常会包含基类的初始化。派生类的构造方法可能会看起来像这样:
```cpp
class People {
public:
// 基类的构造函数
People(string name) : name_(name) {} // 假设name_是一个私有成员变量
private:
string name_;
};
class Student : public People { // 子类继承基类
public:
// 派生类的构造方法,包含了基类的构造
explicit Student(string name, int id) : People(name), studentID(id) {} // 假设studentID也是私有成员变量
private:
int studentID;
};
```
在这个例子中,`Student`的构造方法首先通过`People(name)`调用了基类的构造函数,然后添加了自身的特有属性`studentID`。`explicit`关键字用于指定构造函数,避免隐式转换可能带来的错误。
6-2 写出派生类构造方法(C++) 分数 5 作者 周强 单位 青岛大学 裁判测试程序样例中展示的是一段定义基类People、派生类Student以及测试两个类的相关C++代码,其中缺失了部分代码,请补充完整,以保证测试程序正常运行。 函数接口定义:
以下是完整的代码示例:
```c++
#include <iostream>
using namespace std;
class People {
protected:
string name;
int age;
public:
People(string n, int a) : name(n), age(a) {}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
class Student : public People {
private:
int score;
public:
Student(string n, int a, int s) : People(n, a), score(s) {}
void show() {
display();
cout << "Score: " << score << endl;
}
};
int main() {
Student stu("Tom", 18, 90);
stu.show();
return 0;
}
```
其中,派生类 `Student` 的构造方法如下所示:
```c++
Student(string n, int a, int s) : People(n, a), score(s) {}
```
在构造方法中,首先使用 `:` 符号调用基类 `People` 的构造方法,并传入参数 `n` 和 `a`,然后再初始化派生类 `Student` 的成员变量 `score`。
阅读全文
相关推荐















