Accessing public members of base class fails

旧街凉风 提交于 2019-12-11 11:04:17

问题


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]

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7281072/accessing-public-members-of-base-class-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!