避免定義基類(base class)虛函數的缺省參數, 如果基類虛函數包含缺省參數, 派生類不要重新定義, 會產生異常;
虛函數(virtual)是動態綁定(dynamically bound),缺省參數是靜態綁定(statically bound).
如果派生類(derived class)重新定義缺省值, 實例化, 執行函數正常;
但在動態綁定時, 會出現,執行基類的缺省參數, 卻是派生類的行為, 這樣的異常舉動.
talk is cheap, show you the code.
注意觀察動態綁定時, pr的輸出, 表現為基類的缺省參數, 派生類的動作.
代碼:
/* * test.cpp * * Created on: 2014.04.14 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> #include <string> using namespace std; class Shape { public: enum ShapeColor {Red, Green, Blue}; virtual void draw(ShapeColor color = Red) const = 0; }; class Rectangle : public Shape { public: virtual void draw(ShapeColor color = Green) const { std::cout << "Rectangle : "; switch (color) { case Red : std::cout << "color = " << "Red" << std::endl; break; case Green : std::cout << "color = " << "Green" << std::endl; break; case Blue : std::cout << "color = " << "Blue" << std::endl; break; default: break; } } }; class Circle : public Shape { public: virtual void draw(ShapeColor color) const { std::cout << "Circle : "; switch (color) { case Red : std::cout << "color = " << "Red" << std::endl; break; case Green : std::cout << "color = " << "Green" << std::endl; break; case Blue : std::cout << "color = " << "Blue" << std::endl; break; default: break; } } }; int main() { Rectangle R; Circle C; R.draw(); //C.draw(); //報錯, 靜態綁定無法繼承參數 Shape* pr = new Rectangle; //動態綁定 Shape* pc = new Circle; pr->draw(Shape::Blue); pc->draw(Shape::Blue); pr->draw(); //靜態綁定, 使用基類的默認參數, 完成派生類的動作 pc->draw(); return 0; }