简体   繁体   English

在C ++中使用带有函子的头文件

[英]using header files with functors in c++

I am attempting to use functors in a larger-scope project. 我正在尝试在较大范围的项目中使用函子。 I managed to implement a functor when it was on its own, but I am having a lot of trouble figuring out where I define things in the header file (.h) vs the .ccp file so that I can access my functor in the rest of my program. 我设法单独实现了仿函数,但是在弄清楚我在头文件(.h)与.ccp文件中定义的位置时遇到了很多麻烦,因此我可以在其余部分访问我的仿函数我的程序。 When the functor is all together it appears as such: 当函子全部在一起时,它看起来像这样:

class SpecialAttack {
public:
    SpecialAttack() {};
    virtual bool operator() (double timer) = 0;
};

class BallAttack : public SpecialAttack {
public:
    BallAttack() {};
    virtual bool operator() (double timer) { return (timer==0); }
};

class SpiderAttack : public SpecialAttack {
public:
    SpiderAttack() {};
    virtual bool operator() (double timer) { return true; }
};

double special_attack(double timer, SpecialAttack* func) {
    return (*func)(timer);
}

I cannot figure out how to break this up into the appropriate files so that I can then reference it in the rest of my code. 我无法弄清楚如何将其分解为适当的文件,以便随后可以在其余代码中引用它。 What parts should i put in the .h file and what parts go in the .ccp file? 我应该在.h文件中放入哪些部分,而在.ccp文件中放入哪些部分? Thanks! 谢谢!

Splitting functors between .hpp and .cpp files follows the same pattern of declaration and definition used for any class with member functions. 在.hpp和.cpp文件之间拆分函子遵循与具有成员函数的任何类相同的声明和定义模式。

attack.hpp Attack.hpp

#pragma once

class SpecialAttack {
public:
    SpecialAttack();
    virtual bool operator() (double timer) = 0;
};

class BallAttack : public SpecialAttack {
public:
    BallAttack();
    virtual bool operator() (double timer) override;
};

class SpiderAttack : public SpecialAttack {
public:
    SpiderAttack();
    virtual bool operator() (double timer) override;
};

attack.cpp Attack.cpp

#include "attack.hpp"

SpecialAttack::SpecialAttack() {
}

BallAttack::BallAttack() {
}

/*virtual*/ bool BallAttack::operator() (double timer) /*override*/ {
    return (timer==0);
}

SpiderAttack::SpiderAttack() {
}

/*virtual*/ bool SpiderAttack::operator() (double timer) /*override*/ {
    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM