访问基类的公共成员失败 [英] Accessing public members of base class fails

查看:84
本文介绍了访问基类的公共成员失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个胆小的问题:我有两个类,并将所有变量声明为public.为什么我不能访问派生类中的变量?

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 ++告诉我:vec3d.h:76:3:错误:在此范围内未声明"val"

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.

因为vec3d是模板,并且其基类取决于template参数,所以基类的成员不会在非依赖表达式的派生类中自动显示.最简单的解决方法是使用诸如this->X_val之类的从属表达式来访问基类的成员.

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.

这篇关于访问基类的公共成员失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆