我尝试实现Scott Mayer图书代码示例,该示例是关于通过函数对象调用functor的头文件gameCharachter.h#ifndef GAMECHARACTER_H#define GAMECHARACTER_H#include <iostream>#include <typeinfo>using namespace std;#include <tr1/functional>class GameCharacter;int defaultHealthCalc(const GameCharacter& gc);class GameCharacter{public: typedef std::tr1::function<int (const GameCharacter&)> HealthCalcFunc; explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc) : healthFunc(hcf) { } ~GameCharacter() { } int healthValue() const { return healthFunc(*this); }private: HealthCalcFunc healthFunc;};class EyeCandyCharacter: public GameCharacter // another character{public: explicit EyeCandyCharacter(HealthCalcFunc hcf = defaultHealthCalc) : GameCharacter(hcf) { cout<<typeid(*this).name()<<"::"<<__FUNCTION__<<""<<endl; }};struct HealthCalculator{ /*explicit*/ HealthCalculator() { } int operator()(const GameCharacter& gc) const // calculation function { cout<<typeid(*this).name()<<"::"<<__FUNCTION__<<""<<endl; return 0; }};#endif // GAMECHARACTER_Hmain.cpp是:#include "gamecharacter.h"int main(){ EyeCandyCharacter ecc1(HealthCalculator()); ecc1.healthValue();}为什么function 对象拒绝调用healthvalue()中的operator()函数 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 EyeCandyCharacter ecc1(HealthCalculator());声明一个名为ecc1的函数,该函数接受类型为“指向不带任何参数并返回HealthCalculator的函数的指针”类型的参数,并返回EyeCandyCharacter。我认为这不是您的意图。 (adsbygoogle = window.adsbygoogle || []).push({});
10-04 15:04