## C++ 子類不能重載父類函數 解決方法

#include <iostream>

using namespace std;

class B{

public:

int f(int i) { cout << "f(int): ";

return i+1;

}

// ...

};

class D : public B {

public:

double f(double d) {

cout << "f(double): ";

return d+1.3;

}

// ...

};

int main(){

D* pd = new D;

cout << pd->f(2) << '\n';

cout << pd->f(2.3) << '\n';

}

程序運行結果是：f(double): 3.3
f(double): 3.6而不是某些人（錯誤地）猜想的那樣：f(int): 3
f(double): 3.6

class D : public B {

public:

using B::f;

// make every f from B available

double f(double d) {

cout << "f(double): ";

return d+1.3;

// ...

};

`#include <iostream>using namespace std;class B{ public: int f(int i) { cout << "f(int): "; return i+1; } // ... };class D : public B {public:double f(double d) { cout << "f(double): "; return d+1.3; } // ... };int main(){ 	D* pd = new D;	cout << pd->f(2) << '\n';	cout << pd->f(2.3) << '\n';	return 0;}/*f(double): 3.3f(double): 3.6Press any key to continue*/`

`#include <iostream>using namespace std;class B{ public: int f(int i) { cout << "f(int): "; return i+1; } // ... };class D : public B {public:	using B::f;double f(double d) { cout << "f(double): "; return d+1.3; } // ... };int main(){ 	D* pd = new D;	cout << pd->f(2) << '\n';	cout << pd->f(2.3) << '\n';	return 0;}/*f(int): 3f(double): 3.6Press any key to continue*/`