How does a static object behave in C++? If you declare an object as static, is it instantiated only one time, like C? Can you return a static object by reference?
// File: ex4-14.cpp - Static objects
1
2 #include <iostream>
3 using namespace std;
4
5 class thing {
6 public:
7 thing() { cout<<"thing constructor called for "<<this<<endl; }
8 ~thing() { cout<<"thing destructor called for "<<this<<endl; }
9 };
10
11 thing& funk() {
12 static thing T;
13 cout << "funk() called: &T=" << &T << endl;
14 return T;
15 }
16
17 int main() {
18 cout << &(funk()) << endl;
19 cout << &(funk()) << endl;
20 cout << &(funk()) << endl;
21 return 0;
22 }******* Program output *******
thing constructor called for 0x22640
funk() called: &T=0x22640
0x22640
funk() called: &T=0x22640
0x22640
funk() called: &T=0x22640
0x22640
thing destructor called for 0x22640
How many different objects were created in this program?
沒有留言:
張貼留言