我想傳遞一個指向類方法的指針並從迭代器中調用該函數。當我包含派生對象時,下面的代碼無法編譯。 我試過使用類說明符的類型名稱(例如TC :: * pf),但這不起作用。有人可以建議如何使這項工作?通過迭代器調用函數無法在派生對象上編譯
#include <iostream>
#include <vector>
#include <algorithm>
using std::cout;
using std::endl;
using std::vector;
class Base {
public:
Base(int bval) : bval_(bval) { }
virtual void print() {
cout << "Base: bval:" << bval_ << endl;
}
protected:
int bval_;
};
class Derived : public Base {
Derived(int bval, int dval) : Base(bval), dval_(dval) { }
virtual void print() {
cout << "Derived: bval:" << bval_ << " dval:" << dval_ << endl;
}
private:
int dval_;
};
typedef vector<Base*> MyVecType;
typedef MyVecType::iterator MyVecTypeIter;
template <typename T>
void testFunc(MyVecType& v, T (Base::*pf)()) {
for (MyVecTypeIter iter = v.begin(); iter != v.end(); ++iter) {
((*iter)->*pf)();
}
}
int main() {
MyVecType bvec;
bvec.push_back(new Base(44));
bvec.push_back(new Base(55));
// above compiles and runs ok, but this fails to compile
// with 'no matching function' error:
bvec.push_back(new Derived(66));
testFunc(bvec, &Base::print);
return 0;
}
你不必Derived'的'構造有一個參數(既不公開也不是私有的)...編譯器錯誤給出了一個很大的提示它真的值得閱讀:) –
這不是問題,但不要使用'std :: endl',除非你需要額外的東西。 ''\ n''結束一行。 –