C++笔记——类、对象和封装

类是创建对象的模板和蓝图。类是一组类似对象的共同抽象定义。

对象是类的实例化结果。对象是实实在在的存在,代表现实世界的某一事物。

对象三大关键特性-------------------------------------------

行为:对象能干什么。

状态:对象的属性、行为的结果。

标识:对象的唯一身份。

区别-------------------------------------------------------------

类是静态定义,对象是动态实例。

程序代码操作的是对象而非类,建模得到的是类而非对象。

联系----------------------------------------------------------

类是对象的定义。

对象的产生离不开类这个模板。

类存在的目的是实例化得到对象。

定义一个类的步骤----------------------------------------

定义类名;

编写类的数据成员代表属性

编写类的方法代表行为

类的建模是一个抽象和封装的过程--------------------------

抽象:去掉不关注的、次要的信息而保留重要的信息

封装:信息打包。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;
}






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值