4124人加入学习
(13人评价)
C++编程系列 第二季函数和类

制作于2018.4.2

价格 免费

类作用域

每个类都会定义它自己的作用域。在类的作用域之外,普通的数据和函数成员只能由对象,引用或者指针使用成员访问运算符访问。

对象调用:直接成员运算符(.)

指针调用:间接成员运算符(->)

在类的外部定义成员函数时,必须同时提供类名和函数名。

int Student::sum(Student &s)) //作用域解析运算符(::)

{

}

 

作用域为类的常量

不能直接在类的声明中直接通过const来声明一个常量,这是因为声明类只描述了对象的形式,并没有创建对象。因此,在创建对象前,将没有用于存储值的空间。

const int i = 20;

 

作用域为类的常量

想要获得作用域为类的常量,有2种方式:

1.在类中声明一个枚举。在类声明中声明的枚举的作用域为整个类,因此可以用枚举为整型常量提供作用域为整个类的符号名称。用这种方式声明枚举并不会创建类数据成员,只是为了创建符号常量。

enum{PassingScore = 60};

2.使用static关键字。使用static关键字创建的常量将与其他静态变量存储在一起,而不是存储在对象中。

static const int PassingScore = 60;

 

 

//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_;
	static const int PassingScore = 60;
	//公有接口
public:
	Student(string name, int chinese, int math, int english);
	Student();
	~Student();
	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"

Student::Student(string name, int chinese, int math, int english)
{
	name_ = name;
	chinese_ = chinese;
	math_ = math;
	english_ = english;
}

Student::Student()
{
}

Student::~Student()
{
}

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_ >= PassingScore && s.math_ >= PassingScore && s.english_ >= PassingScore)
	{
		return true;
	}
	else
	{
		return false;
	}
}

//18-类的定义.cpp

#include "pch.h"
#include "student.h"

int main()
{
	//通过构造函数显示的初始化和隐式的初始化
	Student stu1 = Student("Sandy", 50, 120, 110);
	Student stu2("Jane", 110, 90, 100);
	Student stu3;
	/*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;
}

 

[展开全文]

授课教师

SIKI学院老师

课程特色

下载资料(1)
视频(43)