对象

作者: labi3285 | 来源:发表于2017-09-15 13:58 被阅读9次

基本定义

class Box {
    
// 公开
public:
    
    // 静态成员,需要初始化,所有对象共享
    static int boxCreateCount;
    // 静态成员函数
    static int getBoxCreateCount() {
        return boxCreateCount;
    }
    
    // 属性
    int id;

    // 构造方法
    Box() {
        width = 0;
        height = 0;
        boxCreateCount += 1;
    }
    // 构造方法
    Box(double w, double h) {
        width = w;
        height = h;
        boxCreateCount += 1;
    }
    // copy 构造
    Box(const Box &obj) {
        width = obj.width;
        height = obj.height;
        boxCreateCount += 1;
    }
    // 析构函数,在对象销毁的时候的回调
    ~Box() {
        cout << "box" << id << " deinit" << endl;
    }
    
    // 方法
    double area() {
        return width * height;
    }
    
    // 使用this指针
    bool isEqualArea(Box b) {
        return this->width * this->height == b.width * b.height;
    }
    
    // 友元函数(不属于类,可直接调用),可以访问box的私有属性
    // 注:这里采用引用类型,访问的是原对象,不然的话,会创建新的
    friend void log(Box& box) {
        // width, height 为私有
        cout << "w:" << box.width << "\th:" << box.height << endl;
    }

// 私有属性
private:
    // 属性 宽度
    double width;
    // 属性 高度
    double height;
};
// 初始化静态成员变量
int Box::boxCreateCount = 0;

调用:

{
    // 创建
    Box b1;
    Box b2(1, 2);

    // copy,调用copy构造函数
    Box b3 = b2;
    
    // 属性赋值
    b1.id = 1;
    b2.id = 2;
    b3.id = 3;
    
    // 访问方法
    double a = b3.area();
    // 访问静态变量
    int c1 = Box::boxCreateCount;
    // 访问静态成员函数
    int c2 = Box::getBoxCreateCount();
    
    // 调用友元函数,访问私有属性
    log(b3);
    
    // 指针访问形式
    Box *p = &b1;
    double area = p->area();
    int id = p->id;
}
// 执行到这里,对象销毁

访问修饰符

修饰符 作用
public 公开,外部可以访问
protected 保护,子类可以访问
private 私有,内部访问

相关文章

网友评论

      本文标题:对象

      本文链接:https://www.haomeiwen.com/subject/ntdssxtx.html