- 構造函數能夠根據須要定義參數
- 一個類中能夠存在多個重載的構造函數
- 構造函數的重載遵循 C++ 重載規則
class Test { public: Test(int v) { // use v to initialize member. } };
對象定義和對象聲明不一樣編程
- 對象定義 - 申請對象的空間並調用構造函數
- 對象聲明 - 告訴編譯器存在這樣一個對象
Test t; // 定義對象並調用構造函數 int main() { extern Test t; // 告訴編譯器存在名爲 t 的 Test 對象 return 0; }
class Test { public: Test() { }; Test(int v) { }; }; int main() { Test t; // 調用 Test() Test t1(1); // 調用 Test(int v) Test t2 = 2; // 調用 Test(int v) return 0; }
#include <stdio.h> class Test { public: Test() { printf("Test()\n"); }; Test(int v) { printf("Test(int v), v = %d\n", v); }; }; int main() { Test t; // 調用 Test() Test t1(1); // 調用 Test(int v) Test t2 = 2; // 調用 Test(int v) int i(100); printf("i = %d\n", i); return 0; }
輸出: Test() Test(int v), v = 1 Test(int v), v = 2 i = 100
- 通常狀況下,構造函數在定義對象時被自動調用
- 一些特殊狀況下,須要手工調用構造函數
如何建立一個對象數組?數組
#include <stdio.h> class Test { private: int m_value; public: Test() { printf("Test()\n"); m_value = 0; }; Test(int v) { printf("Test(int v), v = %d\n", v); m_value = v; }; int getValue() { return m_value; } }; int main() { Test ta[3] = {Test(), Test(1), Test(2)}; for(int i=0; i<3; i++) { printf("ta[%d].getValue = %d\n", i, ta[i].getValue()); } Test t = Test(100); printf("t.getValue() = %d\n", t.getValue()); return 0; }
輸出: Test() Test(int v), v = 1 Test(int v), v = 2 ta[0].getValue = 0 ta[1].getValue = 1 ta[2].getValue = 2 Test(int v), v = 100 t.getValue() = 100
- 需求: 開發一個數組類解決原生數組的安全性問題
- 提供函數獲取數組長度
- 提供函數獲取數組元素
- 提供函數設置數組元素
IntArray.h安全
#ifndef _INTARRAY_H_ #define _INTARRAY_H_ class IntArray { private: int m_length; int* m_pointer; public: IntArray(int len); int length(); bool get(int index, int& value); bool set(int index, int value); void free(); }; #endif
IntArray.cpp函數
#include "IntArray.h" IntArray::IntArray(int len) { m_pointer = new int[len]; for(int i=0; i<len; i++) { m_pointer[i] = 0; } m_length = len; } int IntArray::length() { return m_length; } bool IntArray::get(int index, int& value) { bool ret = (index >= 0) && (index < length()); if( ret ) { value = m_pointer[index]; } return ret; } bool IntArray::set(int index, int value) { bool ret = (index >= 0) && (index < length()); if( ret ) { m_pointer[index] = value; } return ret; } void IntArray::free() { delete[] m_pointer; }
main.cppcode
#include <stdio.h> #include "IntArray.h" int main() { IntArray a(5); for(int i=0; i<a.length(); i++) { a.set(i, i+1); } for(int i=0; i<a.length(); i++) { int value = 0; if( a.get(i, value) ) { printf("a[%d] = %d\n", i, value); } } a.free(); return 0; }
輸出: a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 a[4] = 5
- 構造函數能夠根據須要定義參數
- 構造函數之間能夠存在重載關係
- 構造函數遵循 C++ 中重載函數的規則
- 對象定義時會觸發構造函數的調用
- 在一些狀況下能夠手動調用構造函數
以上內容參考狄泰軟件學院系列課程,請你們保護原創!對象