#include <iostream>
#include <functional>
class Base
{
public:
virtual ~Base() {}
virtual void f1() const {std::cout<<"Base::f1() called"<<std::endl;}
virtual void f1(int) const {std::cout<<"Base::f1(int) called"<<std::endl;}
virtual void f2() const {std::cout<<"Base::f2() called"<<std::endl;}
};
class Derived : public Base
{
public:
virtual ~Derived() {}
void f1() const {std::cout<<"Derived::f1() called"<<std::endl;}
};
int main()
{
Base base;
Derived derived;
auto func1 = std::bind(static_cast<void(Base::*)()const>(&Base::f1), std::cref(base));
func1();
auto func2 = std::bind(static_cast<void(Derived::*)()const>(&Derived::f1), std::cref(derived));
func2();
auto func3 = std::bind(&Base::f2, std::cref(base));
func3();
auto func4 = std::bind(&Derived::f2, std::cref(derived));
func4();
auto func5 = std::bind(static_cast<void(Base::*)(int)const>(&Base::f1), std::cref(base), std::placeholders::_1);
func5(1);
auto func6 = std::bind(static_cast<void(Derived::*)(int)const>(&Derived::f1), std::cref(derived), std::placeholders::_1); // error line
func6(2);
return 0;
}
當我嘗試構建上面的代碼時,gcc提供了以下錯誤消息。std :: bind從父類的重載函數
test.cpp:34:80: error: invalid static_cast from type ‘void (Derived::)() const’ to type ‘void (Derived::)(int) const’
auto func6 = std::bind(static_cast(&Derived::f1), std::cref(derived), std::placeholders::_1);
我不知道是否有與我可以通過Derived
類綁定Base::f1(int)
任何方法(綁定func6
在這裏成功)。 任何幫助表示讚賞。
你是否想把'Derived :: f1'標記爲'override'? – Tas
@Tas你不需要寫'override'。如果在基類中存在具有相同簽名的虛擬函數,它將隱含地覆蓋它。只有*肯定*你會覆寫你寫的'override'。 – Rakete1111
在'Derived'中添加'使用Base :: f1;'將會起作用。可能的重複[C++問題與繼承類中的函數重載](http://stackoverflow.com/questions/14212190/c-issue-with-function-overloading-in-an-inherited-class) – neuront