[英]Accessing public members of base class fails
might be a bit of a coward-ish question: I've got two classes, and declared all variables public. 可能是个胆小的问题:我有两个类,并将所有变量声明为public。 Why can't I access the variables from derived class??
为什么我不能从派生类访问变量?
g++ tells me: vec3d.h:76:3: error: 'val' was not declared in this scope g ++告诉我:vec3d.h:76:3:错误:未在此范围内声明'val'
template<typename TYPE>
class vec{
public:
TYPE *val;
int dimension;
public:
vec();
vec( TYPE right );
vec( TYPE right, int _dimension );
[etc]
template<typename TYPE>
class vec3d : public vec<TYPE>{
public:
vec3d() : vec<TYPE>( 0, 3 ){};
vec3d( TYPE right ) : vec<TYPE>( right, 3 ){};
vec3d( TYPE X_val, TYPE Y_val, TYPE Z_val ) : vec<TYPE>( 0, 3 ){
val[0] = X_val; //// <----------THIS ONE FAILS!
val[1] = Y_val;
val[2] = Z_val;
};
[etc]
This is purely a lookup issue and nothing to do with access control. 这纯粹是一个查找问题,与访问控制无关。
Because vec3d
is a template and its base class depends on the template parameter, the members of the base class are not automatically visible in the derived class in expression that are non-dependent. 由于
vec3d
是模板,并且其基类取决于template参数,因此基类的成员不会在非依赖表达式的派生类中自动显示。 The simplest fix is to use a dependent expression such as this->X_val
to access members of the base class. 最简单的解决方法是使用诸如
this->X_val
之类的从属表达式来访问基类的成员。
You will need to refer to them via this->val
or vec<TYPE>::val
. 您将需要通过
this->val
或vec<TYPE>::val
引用它们。 There's a good explanation in this answer to a similar question . 这个答案对类似的问题有很好的解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.