程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> C++:虛函數(virtual function)缺省參數的異常表現及正確使用

C++:虛函數(virtual function)缺省參數的異常表現及正確使用

編輯:關於C++

避免定義基類(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;  
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved