1 #pragma once 2 #ifndef STUDENT_ 3 #include <iostream> 4 #include <string> 5 6 using namespace std; 7 8 #endif // !STUDENT_ 9 10 //类的声明 11 class Student 12 { 13 private: 14 //Student类的友元函数,但是不是这个类的函数成员 15 friend void printMath(Student &s); 16 string name_; 17 int chinese_; 18 int math_; 19 int english_; 20 21 public: 22 Student(); //没有参数的构造函数 23 Student(string name, int chinese, int math, int english);//构造函数 24 ~Student();//析构函数 25 //公有函数声明 26 //类成员赋值 27 //void setStudent(string name, int chinese, int math, int english); 28 //由于上面类成员已经赋值,可以直接调式类引用,对类成员进行相加运算。 29 int sum(const Student &s); 30 float avery(const Student &s); 31 bool pass(const Student &s); 32 };
1 #include "stdafx.h" 2 #include "student.h" 3 4 //没有参数的构造函数 5 Student::Student() 6 { 7 } 8 //有参数的构造函数 9 Student::Student(string name, int chinese, int math, int english) 10 { 11 name_ = name; 12 chinese_ = chinese; 13 math_ = math; 14 english_ = english; 15 } 16 17 //析构函数 18 Student::~Student() 19 { 20 21 } 22 23 //函数定义并赋值 24 //void Student::setStudent(string name, int chinese, int math, int english) 25 //{ 26 // name_ = name; 27 // chinese_ = chinese; 28 // math_ = math; 29 // english_ = english; 30 //} 31 32 int Student::sum(const Student &s) 33 { 34 return s.chinese_ + s.math_ + s.english_; 35 } 36 37 float Student::avery(const Student &s) 38 { 39 return (s.chinese_ + s.math_ + s.english_) / 3; 40 } 41 42 bool Student::pass(const Student &s) 43 { 44 if (s.chinese_ >= 60 && s.math_ >= 60 && s.english_) 45 { 46 return true; 47 } 48 else 49 { 50 return false; 51 } 52 } 53 54 void printMath(Student & s) 55 { 56 cout << "数学成绩为:" << s.math_ << endl; 57 }
1 // C++函数和类 20-类对象的声明和使用.cpp: 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include "student.h" 6 7 int main() 8 { 9 //通过构造函数显式的初始化 10 Student stu1=Student("uimodel",100,120,110); 11 //通过构造函数隐式的初始化 12 Student stu2("lebin", 99, 110, 85); 13 //string name1 = "uimodel"; 14 //int chinese1 = 100; 15 //int math1 = 120; 16 //int english1 = 110; 17 //stu1.setStudent(name1, chinese1, math1, english1); 18 int totalScore1 = stu1.sum(stu1); 19 float averyScore1 = stu1.avery(stu1); 20 bool isPassed1 = stu1.pass(stu1); 21 cout << "该学生的总成绩为:" << totalScore1 << endl; 22 cout << "该学生的平均成绩为:" << averyScore1 << endl; 23 if (isPassed1 == true) 24 { 25 cout << "该学生通过了这次考试。" << endl; 26 } 27 else 28 { 29 cout << "该学生没有通过这次考试。" << endl; 30 } 31 32 printMath(stu1);//将对象传进函数 33 34 return 0; 35 }