面向对象C++ 学生类1
类内声明,类外定义
使用类内的成员函数给类内的私有成员赋值,并且成员函数在类内声明,类外定义
#include <iostream> #include <string.h> using namespace std; class Student { private: string name; string sex; float math; float chinese; public: float average; void setname(); void setmath(); void setchinese(); void setsex(); void show_data (); float show_average(); float show_sum() ; }; void Student::setsex() { cin>>sex; } void Student::setname () { cin>>name; } void Student::setmath () { cin>>math; } void Student::setchinese () { cin>>chinese; } float Student::show_average () { cout<<"平均分:"<<(math+chinese)/2<<endl; } float Student::show_sum () { cout<<"总分:"<<math + chinese<<endl; } void Student::show_data() { cout<<"学生姓名:"<<name<<endl; cout<<"学生性别:"<<sex<<endl; cout<<"数学:"<<math<<endl; cout<<"语文:" <<chinese<<endl; } main() { Student a; a.setname(); a.setsex(); a.setmath(); a.setchinese(); a.show_data(); a.show_average(); a.show_sum(); return 0; }
构造函数初始化
使用构造函数给类内的私有变量赋值,并输出学生信息
#include <iostream> #include <string.h> using namespace std; class Student { private: string name; string sex; float math; float chinese; public: Student (string,string,float,float); void show_data (); float show_average(); float show_sum() ; }; Student::Student (string a,string b,float c,float d) { this->name=a; this->sex=b; math=c; chinese=d; } void Student::show_data() { cout<<"学生姓名:"<<name<<endl; cout<<"学生性别:"<<sex<<endl; cout<<"数学:"<<math<<endl; cout<<"语文:" <<chinese<<endl; } float Student::show_average () { cout<<"平均分:"<<(math+chinese)/2<<endl; } float Student::show_sum() { cout<<"总分:"<<math + chinese<<endl; } main() { string a,b; float c,d; cin>>a>>b>>c>>d; Student t(a,b,c,d); t.show_data (); t.show_average(); t.show_sum(); return 0; }

浙公网安备 33010602011771号