C++ 07 —— static

源碼

// 07Static.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream.h"

//1. static local var
class Test
{
public:
    Test()
    {
        cout << "constructor" << endl;
    }
    ~Test()
    {
        cout << "destructor" << endl;
    }
};

void fun()
{
    Test t1;
}
void fun2()
{
    static Test t2;
}
//問題:上例中,t1和t2何時構造?何時析構?

//2. static global function
static fun3()
{}

//問題:這個函數可以被本文件外的其他函數調用嗎?

//3 static data member
class Test2
{
    int i;
    static int j;
public:
    //...
};

//問題:j是什麼意義?何時、如何初始化?

//4. static function member

class 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不是靜態對象

發佈了87 篇原創文章 · 獲贊 13 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章