类是概念,对象是实体
标准的一个类具有两个文件。一个 .h 文件,一个 .cpp 文件,一个放声明,一个放定义
面向对象的基本原则
1:一切都是对象
2:程序运行时一堆对象互相发送消息告诉对方做什么(而不是怎么做)
3:每一个对象有它自己的内存,这个内存里面又是其他对象组成的(对象里面还是对象)
4:每一个对象都有一个类型
5:一个特定类型的所有对象都可以接受相同的消息,所有可以接收相同消息的对象可以认为是同一类型
encapsulation 封装
:: 域的解析符
<class name>::<function name>
::<function> // 用全局函数
::<val> // 用的是全局的那个变量,而不是类里面的
头文件中放声明(declaration)而不是放定义(definition)
declaration:
extern variables
function prototypes
class/struct declaration
#include "xx.h" // 在当前目录寻找
#include <xx.h> // 在系统目录寻找(编译器所认定的头文件所在的目录)
Windows 没有统一放置头文件目录的地方
in c++ #include <xx> same as #include <xx.h>
#include <iostream.h> 就不需要 using namespace std; 而且cout等有些不一样
历史上有c++的版本使用的是#include <iostream.h>,哪个版本有对应的输入输出的东西
standard header file structure
#ifndef HEADER_H_
#define HEADER_H_
// type declaration here...
#endif HEADER_H_
这个标准是为了防止在一个.cpp文件里 include 同一个头文件多次
Tips for header
1: one class declaration per header file
2: associated with one source file in the same prefix of file name (对应的源代码文件用相同的前缀)
3: the contents of a header file is surrounded with #ifndef #define #endif
abstract(抽象) 在看待一个问题时有意的不去看待一些细节
1: abstract is the ability to ignore details of parts to foucus attention
on a higher level of a problem
2: modularization(模块化) is the process of dividing a whole into
well-defined parts, which can be built and examined(仔细检查)
separately, and which interact in well-defined ways.
计算机科学是一种人为科学
learning record code:
#include <iostream>
using namespace std;
class TicketMachine {
public:
TicketMachine(); // 构造函数
virtual ~TicketMachine(); // 析构函数
void showPrompt(); // 以下是成员函数
void getMoney(int money);
void printTicket();
void showBalance();
void printError();
private:
const int PRICE;
int balance;
int total;
};
TicketMachine::TicketMachine() : PRICE(5) // : 初始化成员变量列表
{ // 自动生成构造函数
}
TicketMachine::~TicketMachine()
{ // 自动生成析构函数
}
void TicketMachine::showPrompt()
{
cout << "something" << endl;
}
void TicketMachine::getMoney(int money)
{
balance += money;
}
void TicketMachine::showBalance()
{
cout << balance << endl;
}
int main()
{
TicketMachine tm;
tm.getMoney(100);
tm.showBalance();
return 0;
}