might be a bit开发者_开发知识库 of a coward-ish question: I've got two classes, and declared all variables 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
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. The simplest fix is to use a dependent expression such as this->X_val
to access members of the base class.
You will need to refer to them via this->val
or vec<TYPE>::val
. There's a good explanation in this answer to a similar question.
精彩评论