2012-04-04 91 views
0

我有一个简单的问题。我正在编写C++代码;我在同一个文件中有两个类。一个从另一个继承,我试图使用模板来使这些类更一般化。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 

看来,执行(即:基地)类没有得到正确申报;如果我在继承类中包含typedef和基类的实例变量,我不会收到这些错误。但是,如果我包含基类的所有内容,那么它就毫无意义地使用继承了!我试过做基类的“声明”,正如一些人建议的(即:class Base;),但这似乎没有帮助。

我一直在做这个几个小时谷歌福;如果任何人有任何想法,那将是超级!

+0

'typename CondExec :: Exe','this-> ThisObj'和'this-> Execute()'。 – 2012-04-04 18:15:11

回答

3

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

否则,这些非限定名忽略从属基类。

+0

所以你说我在基类中使用的每个实例变量后,我需要用基类名称来限定类?我想我的困惑是适合限定方法或实例变量的地方 – heisenBug 2012-04-04 18:24:01

+0

@ user1313502:如果类型/变量/函数取决于模板,它需要'Exec ::'(对于类型和函数)或'this- >(用于成员变量)。 – 2012-04-04 18:29:06

+0

@ user1313502是的,这就是我所说的。在查找非限定名称时,将忽略相关基类。这就增加了更多的安全性,以便当一个依赖基类声明该名称的成员时,名称的含义不会从全局声明突然变为基类成员声明。如果你希望它是一个基类成员,你需要在'BaseClass ::'或'this->'的前面加上适当的名称。 – 2012-04-04 20:22:38