C/C++

(二十五)静态成员

2018-11-04  本文已影响0人  RGiskard

static定义全局变量

//Object.h
class Object
{
public:
    static int number;
};

//Object.cpp
#include "Object.h"
int Object::number = 1;

//main.cpp
#include<stdio.h>
#include "Object.h"
int main()
{
    Object::number = 2;
    printf("%d\n",Object::number);
    return 0;
}
//Object.cpp
#include "Object.h"
int Object::number = 1;
int main()
{
    Object::number = 2;
}

与普通成员的区别

class Object
{
public:
    int a;
public:
    static int b;
};

Object::a = 1;
Object::b = 2;

sizeof(Object)的值为4,因为它包含一个成员变量a,而b则不计入总大小

class Object
{
public:
    int a;
public:
    static void Set()
    {
        this->s = 1;
    }
};

static语法的特点

//Object.h
class Object
{
public:
    void call();
private:
    static void Test();
};

//Object.cpp
#include "Object.h"
void Object::Test()
{
    printf("...");
}
void Object::Call()
{
    Test(); //从内部调用的时候,Object::可以忽略,加上也行
    //Object::Test();
}

//main.cpp
#include "Object.h"
int main()
{
    //Object::Test;   错误!由于是private,不允许被外部调用
    Object obj; 
    Obj.Call(); //可以通过调用Call间接调用Test
}
//Object.h
class Object
{
private:
    void DoSomething();
    int x,y;
public:
    static void Test(Object* obj); 
};

//Object.cpp
//这里要赋给x,y值,由于Object没有this指针,所以只能显式地传入一个对象
void Object::Test(Object* obj)
{
    obj->x = 1;
    obj->y = 2;
    obj->DoSomething();
}
void Object::DoSomething
{
    printf("...");
}

//main.cpp

Object obj;
Object::Test(&obj);
上一篇 下一篇

猜你喜欢

热点阅读