跳转至

Week5

Class

class是抽象层次的提取.

首先看这个实例:

example
#include <iostream>
using namespace std;
// -------------------Interface --------------------
struct Point{
    int px, py;
};
void point_init(Point *p, int ix, int iy);
void point_print(const Point *p);
void point_move(Point *p, int dx, int dy);
// -------------------Implementation ----------------
void point_init(Point *p, int ix, int iy){
    p->px = ix;
    p->py = iy;
}
void point_print(const Point *p){
    cout << "(" << p->px << ", " << p->py << ")" << endl;
}
void point_move(Point *p, int dx, int dy){
    p->px += dx;
    p->py += dy;
}
// -------------------Test --------------------------
int main(){
    Point p;
    point_init(&p, 2, 3);
    point_print(&p);
    point_move(&p, 5, 7);
    point_print(&p);
    return 0;
}

函数可以被放进struct中,成为专用参数.

optimized
#include <iostream>
using namespace std;
// -------------------Interface --------------------
class Point{
private:
    int px, py; // 不允许从外界直接修改;如果不标注,默认是private
public:
    void init(int ix, int iy){
        this->px = ix;
        this->py = iy;
    }

    void print(){
        cout << "(" << this->px << ", " << this->py << ")" << endl;
    }

    void move(int dx, int dy){
        this->px += dx;
        this->py += dy;
    }
};
// -------------------Test --------------------------

int main(){
    Point p;
    p.init(2, 3);
    p.print();
    p.move(5, 7);
    p.print();
    return 0;
}

进一步地,可以拆分成point.hmain.cpp

point.h和point.cpp

point.h:

#ifndef POINT_H
#define POINT_H // 意思是,如果没有定义这个宏,就把下面的包括进去,否则直接跳到#endif. 作用是防止多重定义.

class Point {
private:
    int px, py;

public:
    void init(int ix, int iy);
    void print();
    void move(int dx, int dy);
};

#endif

point.cpp

#include "Point.h"
#include <iostream>
using namespace std;

void Point::init(int ix, int iy) {
    this->px = ix;
    this->py = iy;
}

void Point::print() {
    cout << "(" << this->px << ", " << this->py << ")" << endl;
}

void Point::move(int dx, int dy) {
    this->px += dx;
    this->py += dy;
}

main.cpp

#include "point.h"

int main() {
    Point p;
    p.init(2, 3);
    p.print();
    p.move(5, 7);
    p.print();
    return 0;
}

第一个编译单元是point.hmain.cpp的组合,会输出main.o;第二个编译单元是iostream,point.h,point.cpp的组合,会输出point.o,最后用linker组合在一起形成整体.

全局变量定义不要放到.h中,而应该放到main.cpp中.