定义成员函数时,需要使用域解析符(::)来标识函数所属的类
void Student::setStudent(string name,int chinese,int math,int english)
{
name_=name }
定义成员函数时,需要使用域解析符(::)来标识函数所属的类
void Student::setStudent(string name,int chinese,int math,int english)
{
name_=name }
类方法定义
定义成员函数时,需使用作用域解析符(::)来标识函数所属的类。
类方法可以访问类的private(私有)成员。
//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;
}
}