【发布时间】:2017-02-05 22:12:10
【问题描述】:
我正在尝试使用模板派生类来实现多态性。见下文:
//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。
是否有其他方法来定义 print_self(),或者这根本不可能?如果不可能,您能否提出另一种方法?
【问题讨论】:
-
使用
this->x和this->y。 -
这里使用
this是多余的。 -
你也可以使用
A<num>::x和A<num>::y或者typedef A<num> base然后base::x等 -
您的代码是正确的。你从哪里得到错误?
-
@Raindrop7 不,它不是多余的,它是必需的。
标签: c++ templates inheritance