面向对象概念备忘

类和对象

构造函数

  • 函数名与类名相同,无返回值。用处:定义对象时自动调用,为对象成员初始化
  • 不带参数,
  • 支持重载

析构函数

  • 函数名是类名前面加”~”。在对象被释放内存前自动执行
  • 作用不是为了删除对象,而是清理对象占用的内存,使这些内存可以供新对象使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;
class Box {
public:
Box(int h = 2, int w = 2, int l = 2);
~Box()
{
cout << "Destructor called." << endl;
}
int volume()
{
return height * width * length;
}

private:
int height, width, length;
};
Box::Box(int h, int w, int len)
{
height = h;
width = w;
length = len;
}
int main()
{
Box box1;
cout << "The volume of box1 is " << box1.volume() << endl;
cout << "hello." << endl;
return 0;
}

静态数据成员

静态成员函数

  • 为了操作静态数据成员

对象的存储空间

特别注意,64位机上,指针占用8个字节

  • 不含数据成员的情况,为1字节(Byte)
  • 成员函数不占空间,即使在成员函数

this指针

虚函数?

继承与派生

0%