C++クラスの関数リロード
2103 ワード
本論文では,C++におけるクラスの関数リロードについて論じる.
次の例
ここには2つの側面があります.クラスDerivedは確かにクラスBaseからdisplay(int)関数を継承しており、自分でも1つのdisplay(int,int)関数を定義しているので、クラスDerivedには2つのdisplayという関数があります. しかしクラスBaseから継承されたdisplay(int)は,継承された後,クラスDerived定義のdisplay(int,int)関数によってブロックされる.
だからコンパイラはp_を呼び出していますderived->display(8)の場合、手順は次のとおりです.まずdisplayという関数を探して、クラスDerivedで見つけました. はタイプチェックを行い、失敗し、エラーを報告します.
ここでの問題は、リロードの問題によるもので、C++リロード要件:異なるバージョンのリロード関数ごとに、同じ役割ドメインで発生する必要があります.クラスDerivedでは、2つのdisplay関数がありますが、その役割ドメインはBase::とDerived::の2つのクラス役割ドメインです.
クラスDerivedでdisplay(int,int)関数を再定義し、クラスDerivedでのdisplayのリロードを実現できますが、Baseクラスで複数のdisplayのバージョンが定義されている場合は、すべて書き換えるのではないでしょうか.この場合、C++はusing文を提供してこの問題を解決することができます.
次の例
#include <iostream>
using namespace std;
class Base{
public:
int display(int n_count){
cout <<"display function defined in the Class Base"<<endl;
return 0;
}
};
class Derived:public Base{
public:
int display(int n_count,int n_width){
cout << "display function defined in the Class Derived"<<endl;
return 0;
}
};
int main(int argc,char** argv){
Base *p_base;
Derived *p_derived = new Derived();
p_base = p_derived;
p_derived->display(8);
p_derived->display(10,20);
return 0;
}
上のプログラムはコンパイルできません.クラスDerivedにはdisplay(int)関数は存在しないので、ここで疑問があります.クラスBaseからdisplay(int)関数を継承したのではないでしょうか.ここには2つの側面があります.
だからコンパイラはp_を呼び出していますderived->display(8)の場合、手順は次のとおりです.
ここでの問題は、リロードの問題によるもので、C++リロード要件:異なるバージョンのリロード関数ごとに、同じ役割ドメインで発生する必要があります.クラスDerivedでは、2つのdisplay関数がありますが、その役割ドメインはBase::とDerived::の2つのクラス役割ドメインです.
クラスDerivedでdisplay(int,int)関数を再定義し、クラスDerivedでのdisplayのリロードを実現できますが、Baseクラスで複数のdisplayのバージョンが定義されている場合は、すべて書き換えるのではないでしょうか.この場合、C++はusing文を提供してこの問題を解決することができます.
using Base::display;
のように、クラスDerivedの定義は次のとおりです.class Derived:public Base{
public:
void function(){
cout<<"virtual function in the Class Derived"<<endl;
}
using Base::display;
int display(int n_count,int n_width){
cout << "display function defined in the Class Derived"<<endl;
return 0;
}
};
は、このような定義に従ってコンパイルを通過する.