任何事物都是一个对象, 也就是传说中的万物皆为对象.
对象的组成:
面向过程的设计:
面向对象的设计:
在 C++ 中, 用类来描述对象. 类属于用户自定的数据类型, 并且该类型的数据具有一定的行为能力, 也就是类中所描述的方法. 通常来说一个类的定义包含两部分的内容, 一是该类的属性, 二是该类的所拥有的方法.
格式:
class 类名 { public: //公共的行为或属性 private: //私有的行为或属性 };
例子:
main.cpp:
#include "Student.h" using namespace std; int main() { Student student1(1, "Little white", 'f'); student1.display(); return 0; }
Student.cpp:
#include "Student.h" #include <iostream> using namespace std; Student::Student(int n, string p, char g) { num = n; name = p; gender = g; } void Student::display() { cout << "num: " << num << endl; cout << "name: " << name << endl; cout << "gender: " << gender << endl; }
Student.h:
#ifndef PROJECT1_STUDENT_H #define PROJECT1_STUDENT_H #include <string> using namespace std; class Student { private: // 私有成员 int num; // 学号 string name; // 名字 char gender; // 性别 public: Student(int num, string name, char gender); void display(); }; #endif //PROJECT1_STUDENT_H
输出结果:
num: 1
name: Little white
gender: f
类的成员函数是一个类的成员, 在类体重声明.
注: 如果一个类中不包含成员函数, 就等同于 C 语言中的结构体了, 体现不出类在面向对象程序设计中的作用.
一般的做法: 讲需要被外界调用的成员函数指定为 public, 它们是类的对外接口. (有的函数只被本类中的成员函数调用, 以支持其他的函数操作, 应该将它们制定为 private)
私有的成员函数只能被本类中的其他成员函数所调用, 而不能被类外调用. 成员函数可以访问本类中任何成员 (包括私有和公用的), 可以引用在本作用域中有效的数据.
调用成员函数的权限:
访问对象中成员的 3 种方法:
通过对象名和成员运算符访问对象中的成员.
Time 类:
#ifndef PROJECT1_TIME_H #define PROJECT1_TIME_H class Time { private: int hour; int minute; int second; public: void set_time(int h, int m, int s); void show_time(); }; #endif //PROJECT1_TIME_H
main:
int main() { Time time; time.set_time(6, 6, 6); time.show_time(); return 0; }
输出结果:
6:6:6
通过指向对象的指针访问对象中的成员.
Time 类:
#ifndef PROJECT1_TIME_H #define PROJECT1_TIME_H class Time { private: int hour; int minute; int second; public: void set_time(int h, int m, int s); void show_time(); }; #endif //PROJECT1_TIME_H
mian:
int main() { Time time; // 实例化time time.set_time(6, 6, 6); // 设置时间 Time *p = &time; // 定义指针, 指向time地址 p->show_time(); (*p).show_time(); return 0; }
输出结果:
6:6:6
6:6:6
通过对象的引用变量访问对象中的成员.
引用变量共占同一段存储单元. 实际上它们是同一个对象, 只是不同的面子表示而已.
Time 类:
#ifndef PROJECT1_TIME_H #define PROJECT1_TIME_H class Time { private: int hour; int minute; int second; public: void set_time(int h, int m, int s); void show_time(); }; #endif //PROJECT1_TIME_H
mian:
int main() { Time time1; // 实例化time time1.set_time(6, 6, 6); // 设置时间 Time &time2 = time1; time2.show_time(); return 0; }
输出结果:
6:6:6
使用内置函数只是影响编译过程. 使用内置函数可以节省运行时间, 但却增加了目标程序的长度:
内置函数:
例子:
# include <iostream> using namespace std; inline int max(int, int, int); int main() { int i = 10, j = 20, k = 40, m; m = max(i, j, k); cout << "max= " << m << endl; return 0; } inline int max(int a, int b, int c){ a = b > a ? b : a; a = c > a ? c : a; return a; }