struct thing { char * pn; int m; }; thing amabob = {"wodget", -23}; // valid initialization Stock hot = {"Sukie's Autos, Inc.", 200, 50.25}; // No! compile error
出錯緣由:數據訪問狀態私有(可改成公有,但違背數據隱藏的初衷)程序員
專門用於構造新對象(建立對象)、將值賦給它們的數據成員(初始化)。函數
Stock food = Stock("World Cabbage", 250, 1.25); // 顯示調用
Stock garment("Furry Mason", 50, 2.5) // 隱式調用
結構更緊湊設計
Stock *pstock = new Stock("Electroshock Games", 18, 19.0) // 結合new使用隱式調用
Classname object = value; // 初始化
這項特性可能致使問題,但能夠關閉(之後補上方法)對象
——在未提供顯示初始值時,用來建立對象的構造函數:blog
Stock fluffy_the_cat; // use the default constructor
Stock::Stock() {}
相似於未初始化的int x;get
Stock(cost string & co = "Error", int n = 0, double pr = 0.0); // 定義構造函數時添加參數默認值
Stock();
Stock first; // calls default constructor Stock second(); // declare a function
如第二個:變成了返回Stock對象的函數的聲明原型