C++ 中什麼時候呼叫建構函式?
在本文中,我們將討論建構函式的呼叫時機。本文中包含不同型別的建構函式,包括全域性、區域性、靜態區域性和動態建構函式。
對於全域性物件,建構函式會在進入 main 函式之前被呼叫。
示例
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
MyClass myObj; //Global object
int main() {
cout << "Inside Main";
}輸出
Calling Constructor Inside Main
當物件是非靜態時,建構函式會在執行到達建立物件的位置時被呼叫。
示例
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
int main() {
cout << "Inside Main\n";
MyClass myObj; //Local object
cout << "After creating object";
}輸出
Inside Main Calling Constructor After creating object
當物件是區域性靜態時,其建構函式只會第一次被呼叫,如果再次使用同一個函式,則不會受到影響。
示例
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
void func() {
static MyClass myObj; //Local static object
}
int main() {
cout << "Inside Main\n";
func();
cout << "After creating object\n";
func();
cout << "After second time";
}輸出
Inside Main Calling Constructor After creating object After second time
最後,對於動態物件,當使用 new 運算子建立物件時,建構函式會被呼叫。
示例
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass() {
cout << "Calling Constructor" << endl;
}
};
int main() {
cout << "Inside Main\n";
MyClass *ptr;
cout << "Declaring pointer\n";
ptr = new MyClass;
cout << "After creating dynamic object";
}輸出
Inside Main Declaring pointer Calling Constructor After creating dynamic object
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP