0%

ReLearn C++

类定义

C++ 类的声明和定义通常是分开在两个不同的文件中,分别是 .h 头文件 和 .cpp 文件

定义一个类

  • 头文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // A.h

    class A
    {
    private: //私有属性
    int a;
    void f1();

    protected: //子类可见
    int b;
    void f2(int i);

    public: //公开属性
    int c = 2;
    int f3(int j);

    A(int a, int b); // 构造函数
    ~A(); //析构函数

    };

  • 头文件对应的 cpp 文件

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// A.cpp

/**
* 实现构造函数
*/
A::A(int a, int b):
a(a),
b(b) {

}

// 等价于

/*
A::A(int a, int b) {
this.a = a;
this.b = b;
}
*/

/**
* 实现析构函数
*/
A::~A() {

}

/**
* 实现 f1 方法
*/
void A::f1() {


}

/**
* 实现 f2 方法
*/
void A::f2(int j) {
this.b = j
}

/**
* 实现 f3 方法
*/
int A::f3(int j) {
this.c = j
}

加个鸡腿呗.