我试图建立基类和派生类的模板,但不断收到错误消息。我的定义和实现位于单独的.h
和.cpp
文件中。我写了一个简单的(不工作的)示例。
test.h
#include <iostream>
template<class T>
class base {
public:
base(T);
virtual T do_stuff();
virtual ~base(){};
protected:
T x;
};
template <class T>
class derived: public base<T> {
public:
derived(T);
T do_stuff();
~derived(){};
private:
};
test.cpp
#include "test.h"
template <class T>
base<T>::base(T x_):x(x_) {}
template<class T>
T base<T>::do_stuff() {
return x;
}
template<class T>
derived<T>::derived(T x_):base<T>(x_){}
template<class T>
T derived<T> :: do_stuff() {
return 2 * x;
}
int main(){
base<double> X(10.0);
derived<double> Y(10.0);
std::cout << X.do_stuff() << std::endl;
std::cout << Y.do_stuff() << std::endl;
}
我收到的错误消息是:
test.cpp: In member function ‘T derived<T>::do_stuff()’:
test.cpp:18:11: error: ‘x’ was not declared in this scope
return 2*x;
这类似于我在实际代码中收到的错误消息。当我摆脱模板内容并将T替换为double时,我的示例工作正常。
我想这个错误很简单,但是我找不到答案。预先感谢。