1.Clock示例
(1) 单C++文件
A. 成员函数的实现直接放在类里面,此时为内联函数。 B.
#include <iostream> #include <iomanip> using namespace std; class Clock{ public: void setTime(int h, int m, int s) { hour= h; minute= m; second= s; } void showTime() { cout << hour << ":" << setw(2) << minute << ":" << setw(2)<< second << endl; } private: int hour; // 时 int minute; // 分 int second; // 秒 }; int main(int argc, char** argv) { Clock c1; c1.setTime(12, 0, 0); c1.showTime(); return 0; } |
【中间的教学截图——有Bug】
(2)头文件、源文件分离
1) 头文件
A. C++的头文件一般要加上宏开关(#ifndef ... #endif)
B. 成员函数:可以在头文件中直接定义,也可以只声明(在类外定义)
C. 数据成员: 一般设置为私有或保护类型的访问控制方式,而成员函数视具体的需求,可以为私有、公 有、保护类型。
#ifndef STUDENT_H #define STUDENT_H class Student { public: void setStudent(int id, string name); // 函数声明(原型) void showStudent(); private: int id; string name; }; #endif //STUDENT_H |
2) 源文件
A.
#include "Student.h" void Student::setStudent(int id, string name) { this->id= id; this->name= name; } void Student::showStudent() { cout << "id: " << id << ", name: " << name; } |
3) 主函数
#include "Student.h" int main(int argc, char** argv) { Student std1; std1.setStudent(1, "张三"); std1.showStudent(); return 0; } |
2. 类定义的语法形式
class 类名称 { public: 公有成员(外部接口) private: 私有成员 protected: 保护型成员 } |
3.类内初始值
#include <iostream> #include <iomanip> using namespace std; class Clock{ public: private: int hour= 12; // 时 int minute= 0; // 分 int second= 0; // 秒 }; |
4.类成员的访问控制
(1)公有类型成员 | |
在关键字public后面声明,它们是类与外部的接口(interface),任何外部函数都可以访问公有类型数据和 | |
函数。 (2)私有类型成员 在关键字private后面声明,只允许本类中的函数访问,而类外部的任何函数都不能访问。 如果紧跟在类名称的后面声明私有成员,则关键字private可以省略。 (3)保护类型成员 与private类似,其差别表现在继承与派生时对派生类的影响不同,详见第七章。 5.对象定义的语法 | |
类名 对象名; 例:Clock myClock; | |
【补充】:指针类型解释 |
功能:将通过通信接收的 字符串,转换成float类型的数值。