C++ 07 —— static

来源:互联网 发布:如何卸载mysql 编辑:程序博客网 时间:2024/06/14 00:32

源码

// 07Static.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "iostream.h"//1. static local varclass Test{public:    Test()    {        cout << "constructor" << endl;    }    ~Test()    {        cout << "destructor" << endl;    }};void fun(){    Test t1;}void fun2(){    static Test t2;}//问题:上例中,t1和t2何时构造?何时析构?//2. static global functionstatic fun3(){}//问题:这个函数可以被本文件外的其他函数调用吗?//3 static data memberclass Test2{    int i;    static int j;public:    //...};//问题:j是什么意义?何时、如何初始化?//4. static function memberclass Test3{    static int i;    int j;public:    static void fun1()    {        i++;    }    void fun2()    {        j++;    }};//问题:上例中,fun1可以如何调用?fun2可以是static吗?int main(int argc, char* argv[]){    return 0;}

问题:上例中,t1和t2何时构造?何时析构?

t1在调用时构造,在函数结束时析构。t2在程序开始时构造,在程序结束时析构。

问题:这个函数可以被本文件外的其他函数调用吗?

static修饰的全局函数只能在本文件里使用

问题:j是什么意义?何时、如何初始化?

j是一个类内的共享变量,在程序开始的时候初始化

问题:上例中,fun1可以如何调用?fun2可以是static吗?

可以用Test::fun1的方式调用,fun2不能,因为j不是静态对象