类 Class

Mar 14th, 2019
  • 在其它设备中阅读本文章

Summary

类 (Class) 的食用方法.

Text

类 (Class) 是什么

- 摘自 百度百科
- 摘自 百度百科

类有什么用

e.g. 放在 头文件 里面

类怎么写 / 用

类的写法和结构体差不多.

class /*...*/
{
  public:
    /*...*/

  private:
    /*...*/

  /*还有其它的,没用过*/
};

要注意类后面有一个分号而结构体没有.
申明时像变量一样申明, 访问时像结构体一样访问.

栗子:

class heap
{
  public:
    bool empty()
    {/*...*/}
    void pop()
    {/*...*/}
    void push(int heapps)
    {/*...*/}
    int size()
    {/*...*/}
    int top()
    {/*...*/}

  private:
    int heaphp[100020], heapcnt;
    void psdown(int heapps)
    {/*...*/}
    void psup(int heapps)
    {/*...*/}
};

heap hp/*申明一个heap*/;

int main()
{
    /*...*/
    hp.top()/*调用top函数*/;
    /*...*/
}

这里值得注意的是你可以访问的变量 / 调用的函数只有

empty()
pop()
push(heapps)
size()
top()

, 即申明在 public 当中的, 申明在 private 当中的只能在类中访问 / 调用.

其它细节

在申明函数时, 以下两种写法都是合法的.

class heap
{
  public:
    bool empty()
    {/*...*/}
};
class heap
{
  public:
    bool empty()
};

bool heap::empty()
{/*...*/}

, 然后加到头文件里面, 就可以在程序中调用了.

owo

mo-ha