#include<iostream> #include<string> using namespace std; namespace student2 { class Student { public: Student(int n,string nam,char s,float sco) { num=n; name=nam; sex=s; score=sco; } void show_data(); private: int num; string name; char sex; float score; }; void Student::show_data() { cout<<"num:"<<num<<" name:"<<name<<" sex:"<<sex<<" score:"<<score<<endl; } }
时间: 2024-03-29 09:38:07 浏览: 23
这是一个C++程序,包含了头文件iostream和string,并定义了一个命名空间student2和一个类Student。该类包含了一个构造函数和一个成员函数show_data,构造函数用于初始化类的数据成员,show_data函数用于输出数据成员的值。
该类的数据成员包括num、name、sex和score,分别表示学号、姓名、性别和成绩。show_data函数用于输出这些数据成员的值。
该程序中使用了命名空间student2,可以避免命名冲突。如果在程序中使用了多个类或函数,并且它们的名称相同,可以使用命名空间来区分它们。
相关问题
#include<iostream> #include<string> using namespace std; namespace student1 { class Student { public: Student(int n,string nam,int a,string addr) { num=n; name=nam; age=a; address=addr; } void show_data(); private: int num; string name; int age; string address; }; void Student::show_data() { cout<<"num:"<<num<<" name:"<<name<<" age:"<<age<<" address:"<<address<<endl; } }
这是一个C++程序,包含了头文件iostream和string,并定义了一个命名空间student1和一个类Student。该类包含了一个构造函数和一个成员函数show_data,构造函数用于初始化类的数据成员,show_data函数用于输出数据成员的值。
该类的数据成员包括num、name、age和address,分别表示学号、姓名、年龄和地址。show_data函数用于输出这些数据成员的值。
该程序中使用了命名空间student1,可以避免命名冲突。如果在程序中使用了多个类或函数,并且它们的名称相同,可以使用命名空间来区分它们。
#include <iostream> #include<string> using namespace std; class Student {public: Student(int n, string nam ) {num=n; name=nam; } void display() {cout<<"num:"<<num<<endl; cout<<"name:"<<name<<endl; } protected: int num; string name; }; class Student1: public Student {public: 空缺 {age=a; } void show( ) {display(); cout<<"age: "<<age<<endl; } private: int age; }; class Student2:public Student1 {public: 空缺 {score=s;} void show_all() {show(); cout<<"score:"<<score<<endl; } private: int score; }; int main( ) {Student2 stud(10010,"Li",17,89); stud.show_all( ); 补全 return 0; }
在主函数中,需要补全一个输出语句,以便输出 stud 对象的信息。
可以在 stud.show_all() 函数调用之后,加上一行代码:
```
cout << "Student2 object information:" << endl;
```
这样就可以在输出学生的信息之前,先输出一条描述信息,以便更好地区分输出内容。完整的代码如下:
```
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
Student(int n, string nam) {
num = n; name = nam;
}
void display() {
cout << "num:" << num << endl;
cout << "name:" << name << endl;
}
protected:
int num;
string name;
};
class Student1 : public Student {
public:
Student1(int n, string nam, int a) : Student(n, nam) {
age = a;
}
void show() {
display();
cout << "age: " << age << endl;
}
private:
int age;
};
class Student2 : public Student1 {
public:
Student2(int n, string nam, int a, int s) : Student1(n, nam, a) {
score = s;
}
void show_all() {
show();
cout << "score: " << score << endl;
}
private:
int score;
};
int main() {
Student2 stud(10010, "Li", 17, 89);
cout << "Student2 object information:" << endl;
stud.show_all();
return 0;
}
```
执行程序后,输出结果如下:
```
Student2 object information:
num:10010
name:Li
age: 17
score: 89
```