类是创建对象的模板和蓝图。类是一组类似对象的共同抽象定义。
对象是类的实例化结果。对象是实实在在的存在,代表现实世界的某一事物。
对象三大关键特性-------------------------------------------
行为:对象能干什么。
状态:对象的属性、行为的结果。
标识:对象的唯一身份。
区别-------------------------------------------------------------
类是静态定义,对象是动态实例。
程序代码操作的是对象而非类,建模得到的是类而非对象。
联系----------------------------------------------------------
类是对象的定义。
对象的产生离不开类这个模板。
类存在的目的是实例化得到对象。
定义一个类的步骤----------------------------------------
定义类名;
编写类的数据成员代表属性;
编写类的方法代表行为。
类的建模是一个抽象和封装的过程--------------------------
抽象:去掉不关注的、次要的信息而保留重要的信息。
封装:信息打包。OOP三大特性:封装、继承、多态。
类不仅可以保护数据,还可以提供成员函数操作数据。
class 类名称{
public:
// 公有函数
protected:
// 保护成员
private:
// 私有函数
// 私有数据成员
int val; // 数据成员
};
main.cpp
#include <iostream>
#include "car.h"
using namespace::std;
void foo(Car *pcar) // 用指针来调用成员函数
{
pcar -> stop();
pcar -> print();
}
void bar(Car& rCar) // 用对象的引用来调用成员函数
{
rCar.stop();
rCar.print();
}
int main()
{
Car a;
cout << sizeof(a) << endl;
cout << "The address of a is " << &a << endl;
a.setProperty(10000, 10001);
a.run();
foo(&a);
bar(a);
return 0;
}
car.h
#ifndef CAR_H_INCLUDED
#define CAR_H_INCLUDED
class Car{
public:
void run();
void stop();
void setProperty(int price, int carNum);
void print();
private: // 数据成员私有
int m_price;
int m_carNum;
};
#endif // CAR_H_INCLUDED
car.cpp
#include <iostream>
#include "car.h"
using namespace::std;
void Car::run()
{
cout << "Car run" << endl;
}
void Car::stop()
{
cout << "Car stop" << endl;
}
void Car::setProperty(int price, int carNum)
{
this -> m_price = price; // this: 成员函数中,当前对象的指针
this -> m_carNum = carNum;
}
void Car::print()
{
cout << "in " << __func__ << " this = " << this << endl;
}