我正在尝试使用模板化派生类来实现多态性。见下文:
//templated base class
template <class num> class A{
protected:
num x;
num y;
public:
A( num x0 = 0, num y0 = 0) {
x = x0;
y = y0;
}
virtual void print_self() = 0;
};
//derived class
template < class num > class B: public A < num > {
public:
B( num x1 = 0, num y1 = 0):shape < num > ( x1 , y1 ) { }
void print_self(){
std::cout << "x is " << x << " and y is " << y << endl;
}
};
基类具有纯虚函数 print_self()。当尝试在派生类中定义函数时,我收到以下错误:
'x' was not declared in this scope
y 也一样。 因此,派生类无法访问变量 x 和 y,即使它被列为 protected 。
是否有其他方法来定义 print_self(),或者这根本不可能?如果不可能,您能建议另一种方法吗?
最佳答案
由于您使用的是模板化继承,因此 x
和 y
的存在取决于模板参数。换句话说,this
指针的基类部分成为依赖名称。您必须显式使用 this
指针或使用 using。
template<typename num>
struct B : A<num> {
using A<num>::x;
using A<num>::y;
void print_self(){
std::cout << "x is " << x << " and y is " << y << endl;
}
};
或者甚至:
template<typename num>
struct B : A<num> {
void print_self() {
std::cout << "x is " << this->x << " and y is " << this->y << endl;
}
};
关于c++ - 具有模板化继承的纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057921/