0
点赞
收藏
分享

微信扫一扫

C++ static

笑望叔叔 2022-02-22 阅读 148
/*
* - static
* - 静态变量:当变量被声明为static时,空间将在程序的生命周期内分配;即使多次调用该函数,静态变量的空间也只分配一次,前一次调用中的变量值通过
*   下一次函数调用传递;这对于在C/C++或需要存储先前函数状态的任何其他应用程序非常有用。
* - 类中的静态变量:由于声明为static的变量只被初始化一次,因为它们在静态存储中分配了空间,因此类中的静态变量由对象共享;
*   对于不同的对象,不能有相同静态变量的多个副本,也是这个原因,静态变量不能使用构造函数初始化
*   就像变量一样,对象也在声明为static时具有范围,直到程序的生命周期。
* - 类中的静态函数:就像类中的静态数据成员或静态变量一样,静态成员函数也不依赖于类的对象;我们可以使用对象和'.'来调用静态成员函数,一般使用类名和
*   范围解析运算符调用静态成员;允许静态成员函数仅访问静态数据成员或其它静态成员函数,它们无法访问类的非静态数据成员或成员函数。
*/
#include <iostream> 
#include <string> 
using namespace std;

void func1()
{
    // static variable 
    static int count = 0;
    cout << count << " ";

    count++;
}

class A
{
public:
    static int i;

    A()
    {
        // Do nothing 
    };
};
int A::i = 1;

/*
Inside Constructor
Inside Destructor
End of main
*/
class B
{
    int i;
public:
    B()
    {
        i = 0;
        cout << "Inside Constructor\n";
    }
    ~B()
    {
        cout << "Inside Destructor\n";
    }
};

/*
Inside Constructor
End of main
Inside Destructor
*/
class C
{
    int i;
public:
    C()
    {
        i = 0;
        cout << "Inside Constructor\n";
    }
    ~C()
    {
        cout << "Inside Destructor\n";
    }
};

class D
{
public:
    // static member function 
    static void printMsg()
    {
        cout << "Hello World!" << endl;
    }
};

int main()
{
    for (int i = 0; i < 5; i++) {
        func1(); // 输出0 1 2 3 4
    }
    cout << endl;

    A obj1;
    //A obj2;
    //obj1.i = 1;
    //obj2.i = 2;
    cout << obj1.i <<  endl;

    int x = 0;
    if (x == 0)
    {
        B obj;
    }
    cout << "End of main\n";

    if (x == 0)
    {
        static C obj;
    }
    cout << "End of main\n";

    D::printMsg();

    return 0;
}
举报

相关推荐

0 条评论