您的位置:首页 > 编程语言 > C语言/C++

C++ primer plus 阅读记录-对象和类

2017-05-09 17:59 253 查看


类构造函数,专门用于构造新对象、将值赋给他们的数据成员。程序声明对象时,将自动调用构造函数。

构造函数没有返回类型。

为避免混乱,一种常见的做法是在数据成员名中使用m_前缀。

默认构造函数是没有参数或所有参数都有默认值的构造函数,拥有默认构造函数后,可以声明对象而不初始化它。

析构函数完成清理工作 ~Stock()





this指针

有时类方法可能涉及到两个对象,这种情况下需要使用this指针。this指针指向调用对象。

作用域为类的常量

1. 在类中声明一个枚举

private:

enum {Months = 12};

2. 使用关键字static

private:

static const int Months = 12;

!栈的实现

//stack.h -- class definition for the stack ADT

#ifndef STACK_H_
#define STACK_H_

typedef unsigned long Item;
class Stack
{
private:
enum {MAX = 10};
Item items[MAX];
int top; //index for top stack item

public:
Stack();
bool isempty() const;
bool isfull() const;
bool push(const Item& item);
bool pop(Item& item);
};

#endif


//stack.cpp
#include "stack.h"
Stack::Stack()
{
top = 0;
}

bool Stack::isempty() const
{
return top == 0;
}

bool Stack::isfull() const
{
return top == MAX;
}

bool Stack::push(const Item& item)
{
if(top < MAX)
{
items[top++] = item;
return true;
}
else
return false;
}

bool Stack::pop(Item& item)
{
if(top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: