【C++】学习笔记草稿版系列8(封装)

Encapsulation

struct

struct Man
{
    string name;
    int age;
    float high;
    float salary;
    char sex;
};

struct Date
{
    int year;
    int month;
    int day;
};

int main()
{
    Date d;
    return 0;
}

C语言的封装风格是把数据放到一起打包,使用struct,然后把数据以引用或指针的方式传递给行为。
把对struct的声明放在.h文件里;
把struct对应的行为函数放在对应的.cpp文件里。再定义好自包含,在.cpp里面include,在.h里面写好函数的声明。

C++认为C语言封装不彻底:
1. 数据和行为分离
2. 没有权限控制

封装:对内数据开放,逻辑抽象;对外提供接口

C++默认class内部数据private
// private protected public

C++中static关键词修饰

static 全局变量 外延性 static作用于仅限于本文件

局部变量 auto 生命周期 存储位置

static 在类内部的表现,用来实现族内类对象空间的数据共享。
在生成对象的时候,普通数据成员才有空间。而static成员在类声明的时候,就已经另外开辟了空间。
static数据成员,既属于类,也属于对象,但终归属于类。
类其实本质上也是一个命名空间。
1. 初始化,类内定义,类外初始化。

type 类名:: 变量名 = 初值
  1. static数据成员,既属于类,也属于对象,但最终属于类。
class School
{
public: 
    string tower;
    string lake;

    static string lib;
}
string School::lib = "";
int main()
{
    School::lib = "Essential C++";
    School::lib += "Effective C++";
    School::lib += "More effective C++";
    School tsinghua, peking, fudan;

    tsinghua.lib += "Practice_in_Python";
    peking.lib += "R_in_action";

    cout<<tsinghua.lib<<endl;//可以看到所有的添加的书籍
    return 0;
}

一般数据成员不会公开

static修饰成员函数,作用只有一个,用于管理static成员。
static修饰的成员函数,既属于类也属于对象,终归属于类。
static修饰的成员函数,因为属于类,所以没有this指针,不能访问非static数据成员与成员函数。

class School
{
public:
    string & getTower()
    {return tower;}
    static string& getLib()
    {return lib;}
private:    
    string tower;
    string lake;

    static string lib;
}

static const 成员

const在参数列表里面初始化
static要在外部初始化
static const 就地初始化

static const a = 8;

const和static的练习

class CCSprite
{
public:
    CCSprite(int d)
    {
        data = d;
        if (head == NULL)
        {
            this->next = NULL;
            head = this;
        }
        else
        {
            this->next = head;
            head = this;
        }
    }

    static void traverseCCSprite()
    {
        CCSprite *ph = head;
        while(ph != NULL)
        {
            cout<<ph->data<<endl;
            ph = ph->next;
        }
    }

private:
    int data;
    CCSprite* next;
    static CCSprite * head;
};

int main()
{
    CCSprite a(1), b(2), c(3);//栈
    new CCSprite(4);//堆
    CCSprite::traverseCCSprite();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值