对象的声明与使用
创建对象,最简单的方式是声明类变量,即Student stu1;
使用对象的成员函数和使用结构成员一样,通过成员运算符(.)来使用,即stu1.sum(stu1)。
注意:所创建的每个新对象都有自己的存储空间,用于存储其内部变量和类成员。但是同一个类的所有对象共享同一组类方法。
在OOP中,调用成员函数也被称为发送消息。
//student.h
#pragma once
#ifndef STUDENT_H_
#define STDENT_H_
#include <iostream>
#include <string>
using namespace std;
//class关键字和类名
class Student
{
//私有成员,定义数据成员,只能通过公有接口进行访问,数据隐藏
private:
string name_;
int chinese_;
int math_;
int english_;
//共有接口
public:
void setStudent(string name, int chinese, int math, int english);
int sum(const Student &s);
float avery(const Student &s);
bool pass(const Student &s);
};
#endif // !STUDENT_H_
//student.cpp
#include "pch.h"
#include "student.h"
void Student::setStudent(string name, int chinese, int math, int english)
{
name_ = name;
chinese_ = chinese;
math_ = math;
english_ = english;
}
int Student::sum(const Student & s)
{
return s.chinese_+s.math_ +s.english_;
}
float Student::avery(const Student & s)
{
return(float)(s.chinese_ + s.math_ + s.english_) / 3;
}
bool Student::pass(const Student & s)
{
if (s.chinese_ >= 60 && s.math_ >= 60 && s.english_ >= 60)
{
return true;
}
else
{
return false;
}
}
//18类的定义.cpp
#include "pch.h"
#include "student.h"
int main()
{
Student stu1;
Student stu2;
string name1 = "Sandy";
int chinese1 = 100;
int math1 = 120;
int english1 = 110;
stu1.setStudent(name1, chinese1, math1, english1);
int totalScore1 = stu1.sum(stu1);
float averyScore1 = stu1.avery(stu1);
bool isPassed1 = stu1.pass(stu1);
cout << "该学生的总成绩为:" << totalScore1 << endl;
cout << "该学生的平均成绩为:" << averyScore1 << endl;
if (isPassed1 = true)
{
cout << "该学生通过了这次考试。" << endl;
}
else
{
cout << "该学生没有通过这次考试。" << endl;
}
return 0;
}