class2

再论class

public or private?

class Rect{
    ...
private:
    int w,h;
};
int area(Rect & rect){
    return rect.w * rect.h;
}

friend(友元)

class Rect{
    ...
private:
    int w,h;
    friend int area(Rect & rect);
};
int area(Rect & rect){
    return rect.w * rect.h;
}

另一个friend的例子


list & Iterator(迭代器)

protected


家族可见性

protected inherited


保护继承

利用全局变量计数

int point_count = 0;
class Point{
public:
    Point(){
        point_count++;
    }
    ~Point(){
        point_count--;
    }
};

static(静态)成员

class Point{
public:
    Point(){
        count++;
    }
    ~Point(){
        count--;
    }
private:
    static int count;
};
int Point::count = 0;

singleton(单例模式)

class MyClass{
public:
    static MyClass *getInstance(){
        if(instance==NULL)
            instance=new MyClass();
        return instance;
    }
private:
    static MyClass *instance;
    MyClass(){}
};
MyClass *MyClass::instance=NULL;
void main()
{
    MyClass *obj;
    obj=MyClass::getInstance();
}

const object


常对象

multiple inheritance(多继承)

class LionTiger:public Lion,public Tiger{
    ...
};

单继承的内存结构示意图

多继承的内存结构示意图(一)

多继承的内存结构示意图(二)

代码执行顺序问题


1)构造函数 vs 析构函数

2)子对象声明顺序 vs 构造函数初始化列表

3)父类 vs 子类

类似于堆栈: FILO

最先创建 的 最后销毁 !!!



The End

目录