1. 程式人生 > >HOUR 14 Calling Advanced Functions

HOUR 14 Calling Advanced Functions

[] tor else stat 引用 參數 ostream 理解 nth

默認參數

函數重載和默認參數函數會達到同樣的效果。默認參數寫起來簡單,理解起來難。

默認構造參數有個缺點是,當參數不斷增加的時候,理解起來會有點困難。

#include <QCoreApplication>
#include <iostream>

class Rectangle
{
public:
    Rectangle(int aWidth, int aHeight);
    ~Rectangle() {}
    void drawShape(int aWidth, int aHeight, bool useCurrentValue = false) const
; private: int width; int height; }; Rectangle::Rectangle(int aWidth, int aHeight) { width = aWidth; height = aHeight; } void Rectangle::drawShape(int aWidth, int aHeight, bool useCurrentValue) const { int printWidth; int printHeight; if (useCurrentValue == false) { printHeight
= aHeight; printWidth = aWidth; } else { printHeight = height; printWidth = width; } for(int i = 0; i < printHeight; i++) { for(int j = 0; j < printWidth; j++) std::cout << *; std::cout << std::endl; } }
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Rectangle box(10, 2); box.drawShape(5, 5); box.drawShape(5, 5, true); return a.exec(); }

構造函數重載:構造函數的創建分為兩個階段

  1. 初始化階段
  2. 函數體階段
Tricycle::Tricycle() :
    speed(5),
    wheelSize(12)
{
    //other statements
}

構造函數後面的冒號表示要開始初始化了, 函數體完成其他的賦值操作。

常量變量和引用必須在初始化的時候給定值,所以類內的引用、const等必須用這種技術

Copy Constructor

編譯器會自動創建復制構造函數,每次發生復制時候調用。

當向一個類中傳值的時候,就會調用復制構造函數創建一個臨時復制的對象。

復制構造函數只接受一個參數——指向同一類對象的引用,由於復制不會改變傳入的對象,所以最好定義為const類型的,例如

Tricycle(const Tricycle &trike);

HOUR 14 Calling Advanced Functions