访问基类的公共成员失败
可能是一个有点胆怯的问题:我有两个类,并将所有变量声明为公共。为什么我无法访问派生类中的变量?
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]
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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这纯粹是一个查找问题,与访问控制无关。
由于 vec3d 是一个模板,并且其基类依赖于模板参数,因此基类的成员在派生类的非依赖表达式中不会自动可见。最简单的修复方法是使用依赖表达式(例如
this->X_val
)来访问基类的成员。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 asthis->X_val
to access members of the base class.您需要通过
this->val
或vec::val
引用它们。 类似问题的答案。You will need to refer to them via
this->val
orvec<TYPE>::val
. There's a good explanation in this answer to a similar question.