1.通过对象名和成员运算符访问对象中的成员
2.通过指定对象的指针访问对象中的成员
3.通过对象的引用访问对象中的成员
2.4.1通过对象名和成员运算符访问对象中的成员
1. "."是成员运算符,指明访问的是哪个对象中的成员
2.访问对象中的成员模板: 对象名.成员名
例:
stud1.display()
注意:在类外只能访问public成员,一个类中至少得有一个public成员函数,作为对外接口,否则就无法对对象进行任何操作。
2.4.2 通过引用指向对象的指针访问对象中的成员
class Time
{
public: //公有数据成员
int hour;
int minute;
};
Time t,*p; //定义对象t和指针变量p
p=&t; //使p指向对象t
cout << p -> hour; //输出p指向的对象中的成员hour
p->hour表示p当前指向的对象t中的成员hour,(*p).hour也是对象中的成员hour,在p的指引下,p->hour,(*p).hour,t.hour三者等价
2.4.3通过对象的引用来访问对象中的成员
引用表示与其代表的变量共享同一存储空间,也可以通过引用的方式来访问对象中的成员。
Time t1; Time &t2=t1; cout << t2.hour2.5类和对象的简单应用举例
例1:用类来实现输入和输出时间(时:分:秒)
#incliudeusing namespace std; class Time{ public: int hour; int minute; int sec; }; int main(){ Time t1; cin >> t1.hour; cin >> t1.minute; cin >> t1.sec; cout << t1.hour<< ":" << t1.minute << ":" << t1.sec << endl; return 0; }
例2: 用上述Time类,定义多个对象,分别输入输出各对象中的时间
#includeusing namespace std; class Time{ public: int hour; int minute; int sec; }; int main(){ Time t1; cin >> t1.hour; cin >> t1.minute; cin >> t1.sec; cout << t1.hour<< ":" << t1.minute << ":" << t1.sec << endl; Time t2; cin >> t2.hour; cin >> t2.minute; cin >> t2.sec; cout << t2.hour<< ":" << t2.minute << ":" << t2.sec << endl; }
改良:使用函数
#includeusing namespace std; class Time { public: int hour; int minute; int sec; }; int main() { void set_time(Time&); void show_time(Time&); Time t1; set_time(t1); show_time(t1); Time t2; set_time(t2); show_time(t2); return 0; } void set_time(Time& t) { cin >> t.hour; cin >> t.minute; cin >> t.sec; } void show_time(Time& t) { cout << t.hour << ":" << t.minute << ":" << t.sec << endl; }
改进:增加成员函数
#includeusing namespace std; class Time { public: void set_time(); void show_time(); private: int hour; int minute; int sec; }; int main() { Time t1; t1.set_time(); t1.show_time(); Time t2; t2.set_time(); t2.show_time(); return 0; } void Time::set_time() { cin >> hour; cin >> minute; cin >> sec; } void Time::show_time() { cout << hour << ":" << minute << ":" << sec << endl; }
例3:找出一个整数型数组中的元素的最大值
#include2.6类的封装性和信息隐蔽using namespace std; class Array_max { public: void set_value(); //为数组赋值 void max_value(); //寻找最大值 void show_value(); //输出最大值 private: int array[10]; int max; }; void Array_max::set_value() { int i; for (i = 0;i<10;i++) cin >> array[i]; } void Array_max::max_value(){ int i; max = array[0]; for (i = 1; i < 10; i++) { if (max < array[i]) max = array[i]; } } void Array_max::show_value() { cout << "the max is" << max; } int main() { Array_max arrmax; arrmax.set_value(); arrmax.max_value(); arrmax.show_value(); return 0; }
2.6.1 概念
封装性 :把数据和关于操作的算法封装在类类型中
类的接口 :共有成员函数,通过调用共有成员函数来实现对类的使用
类的私有实现 : 通过成员函数对数据成员进行操作,如果类中的操作的数据是私有的,类的功能的实现对用户是隐蔽的
信息隐蔽 : 类的公用接口和类的私有实现的分离
2.6.2 C++程序的组成
(1) 类声明头文件(.h或无后缀文件)
(2)类实现文件(.cpp).包含类成员函数的定义
(3)类的使用文件(.cpp),即主文件



