0

我有一个快速的问题。我正在编写 C++ 代码;我在同一个文件中有两个类。一个继承自另一个,我正在尝试使用模板使类更通用。

这是基类的文件:

template<class E> // this is the class we will execute upon
class Exec{

protected: 

    typedef void (*Exe)(E*); // define a function pointer which acts on our template class.

    Exe* ThisFunc; // the instance of a pointer function to act on the object
    E* ThisObj;    // the object upon which our pointer function will act

public:

    Exec(Exe* func, E* toAct){ThisFunc = func; ThisObj=toAct;} 
    Exec(){;} // empty constructor

void Execute(){ThisFunc(ThisObj);} // here, we pass our object to the function

};

这是继承的类:

template<class E> // this is the class we will execute upon
class CondExec : protected Exec<E>{ // need the template!

protected:

    typedef bool (*Cond)(E*); // a function returning a bool, taking a template class
    Cond* ThisCondition;

public:

CondExec(Exe* func, E* toAct,Cond* condition): Exec<E>(func,toAct){ThisCondition=condition;}

void ExecuteConditionally(){
    if (ThisCondition(ThisObj)){
        Execute();
        }
    }
};

但是,当我尝试此操作时,出现以下错误:

executables.cpp:35: error: expected `)' before ‘*’ token
executables.cpp: In member function ‘void CondExec<E>::ExecuteConditionally()’:
executables.cpp:37: error: ‘ThisObj’ was not declared in this scope
executables.cpp:37: error: there are no arguments to ‘Execute’ that depend on a template             parameter, so a declaration of ‘Execute’ must be available

似乎 Exec (即:基)类没有得到正确声明;如果我在继承类中包含来自基类的 typedef 和实例变量,我不会收到这些错误。但是,如果我包含基类中的所有内容,那么使用继承毫无意义!

正如一些人所推荐的那样,我已经尝试过对基类进行“声明”(即:class Base;),但这似乎没有帮助。

几个小时以来,我一直在做一些 google-fu;如果有人有任何想法,那就太好了!

4

1 回答 1

3

你需要说typename Exec<E>::Exe。因为基类是依赖的。执行相同,您需要使用前面的基类名称来限定调用:Exec<E>::Execute();

否则,那些不合格的名称会忽略依赖的基类。

于 2012-04-04T18:13:51.243 回答