2020年6月24日 星期三

函數中的靜態變數

函數中的靜態變數只在第一次呼叫這個函數才會建立,之後不管呼叫幾次都用的都是同一個,包括成員函數也一樣。如以下的範例:
 
#include <iostream>

using namespace std;

class A
{
  int m_v;
public:
  // Constructor
  A(int v)
  {
    m_v = v;
  }

  void Show()
  {
    cout << "數值:" << m_v << endl;
  }
};

class B
{
public:
  // Constructor
  B()
  {}

  void Show(int v)
  {
    static A a(v); // 函數中的靜態變數
    a.Show();
  }
};


int main()
{
  B b1;
  B b2;

  b1.Show(1); // 第一次執行會設定靜態變數,往後用的都是同一個
  b1.Show(11);

  b2.Show(2);
  b2.Show(22);

  return 0;
}




2 則留言:

  1. Top 10 Casinos in Las Vegas, NV | MapYRO
    Top 10 남양주 출장마사지 Casinos in 아산 출장안마 Las Vegas, NV. 수원 출장샵 A popular casino with a lot 의정부 출장안마 to recommend. Casino: 전라북도 출장마사지 35 Casino Rooms, 7 Casino Hotel Rooms, 15 Casino

    回覆刪除
  2. Therefore, we’ve outlined the process of registering 코인카지노 an account, together with how the verification course of works. Playing at a reside supplier on line casino on-line is as close to a real on line casino experience as you would get and we extremely advocate you check it out. The reason for that is that Evolution Gaming has developed one of the best reside on line casino software in the world and so they present a number of the} most experienced dealers in the business. Keep in thoughts that these video games are performed towards the pc and are due to this fact the true deal. Instead, we suggest you take a look at|try} Jackpot City’s reside dealers. As mentioned earlier, this is a a|it is a} Microgaming on line casino meaning they only offer on line casino video games and slots from that developer.

    回覆刪除