无法访问受保护的成员 [英] Cannot access protected member

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

问题描述


可能重复:

不能调用基类保护函数?


不理解以下情况,当 Derived 继承自 Base 时,它可以访问其受保护的成员通过Derived函数。但是如果 Base 类尝试从 Derived 类访问其自己的成员(本身允许访问 Base ),它无法访问,为什么?

  class Base {
protected:
int x;
};

class Derived:Base {
public:
void foo(Base * b);
};


void Derived :: foo(Base * b){
b-> x = 2; //无法访问受保护的成员,
//虽然Derived继承自Base,为什么?
}


解决方案

p>

内部 Derived :: foo(),可以访问派生。但是, * b Derived 类型的不是。相反,它是 Base 类型,因此它与您的类没有任何关系。



不同的事情,如果你以一个 Derived * 作为参数 - 那么你确实可以访问受保护的基本成员。






让我们拼出来:

  struct Derived; 

struct Base
{
int f(Derived *);
protected:
int x;
private:
int y;
};

struct Derived:public Base
{
int g(Base *);
int h(Derived *);
};

int Derived :: g(Base * b)
{
return b-> x; //错误,无关类的protected成员
return b-> y; //错误,不同类的私有成员
}

int Derived :: h(Derived * d)
{
return d-> x; // OK,protected base member accessible in derived class
return d-> y; //错误,不同类的私有成员
}

int Base :: f(Derived * d)
{
return d-> x; // OK,d convert to Base *
return d-> y; // OK,ditto
}


Possible Duplicate:
cannot call base class protected functions?

I don't understand the following, when Derived inherits from Base, it gets access to its protected members which can be accessed through Derived functions. But if, Base class tries to access its own members from Derived class (which itself allows access to Base), it doesn't get access, why?

class Base {
protected:
    int x;
};

class Derived : Base {
public:
    void foo(Base* b);
};


void Derived::foo(Base* b) {
    b->x = 2;       // cannot access protected member,
                    // though Derived inherits from Base, why?
}

解决方案

A common misunderstanding.

Inside Derived::foo(), you can access protected base members of objects of class Derived. However, *b is not of type Derived. Rather, it is of type Base, and so it does not have anything to do with your class.

It's a different matter if you take a Derived* as an argument -- then you will indeed have access to protected base members.


Let's spell it out:

struct Derived;

struct Base
{
  int f(Derived *);
protected:
  int x;
private:
  int y;
};

struct Derived : public Base
{
  int g(Base *);
  int h(Derived *);
};

int Derived::g(Base * b)
{
   return b->x; // error, protected member of unrelated class
   return b->y; // error, private member of different class
}

int Derived::h(Derived * d)
{
  return d->x;  // OK, protected base member accessible in derived class
  return d->y;  // error, private member of different class
}

int Base::f(Derived * d)
{
  return d->x;  // OK, d converts to Base*
  return d->y;  // OK, ditto
}

这篇关于无法访问受保护的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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