C++面向对象类的实例题目七
题目描述:
编写两个有意义的类,使一个类嵌套在另一个类中。
分析:
本题涉及两个类student和cdegree,前者为学生类,包含学生的学号(nubner),姓名(name)和成绩(degree),而成绩degree是类cdegree的对象。cdegree类有3个数据成员,分别为数学(math),英语(english)和物理(phy)分数。
程序代码:
#include<iostream> #include<string> using namespace std; class Student { public: void getdata(); void showdata(); private: string number; string name; class Cdegree { public: double math; double english; double phy; }degree; }; void Student::getdata() { cout<<"Input number:"; cin>>number; cout<<"Input name:"; cin>>name; cout<<"Input degree of math:"; cin>>degree.math; cout<<"Input degree of english:"; cin>>degree.english; cout<<"Input degree of physics:"; cin>>degree.phy; } void Student::showdata() { cout<<"=========分割线======="<<endl; cout<<"Number:"<<number<<endl; cout<<"Name:"<<name<<endl; cout<<"Math"<<degree.math<<endl; cout<<"English:"<<degree.english<<endl; cout<<"Physics:"<<degree.phy<<endl; } int main() { Student s1; s1.getdata(); s1.showdata(); return 0; }
结果输出:
Input number:007 Input name:qianshou Input degree of math:89 Input degree of english:99 Input degree of physics:100 =========分割线======= Number:007 Name:qianshou Math89 English:99 Physics:100