Chinaunix首页 | 论坛 | 博客
  • 博客访问: 988570
  • 博文数量: 158
  • 博客积分: 4380
  • 博客等级: 上校
  • 技术积分: 2367
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-21 10:45
文章分类

全部博文(158)

文章存档

2012年(158)

我的朋友

分类: C/C++

2012-11-23 16:31:00

问题的发现:
不能通过编译的代码一:

class Base
{
protected:
    
void bar()
    
{
    }

}
;

class Device: public Base
{
public:
    Device()
    
{
        Base::bar(); 
// OK
        &Base::bar; // cannot access protected member
    }

}
;

不能通过编译的代码二:

class Base
{
protected:
    Base( 
int )
    
{
    }

}
;

class Device : public Base
{
public:
    Device() : Base(
0// OK
    {
        Base b(
1); // cannot access protected member
    }

}
;

猜想:对于派生类,protected的受作用者是对象而不是类

用代码来证明:

class Base
{
protected:
    
int x;
}
;

class Device : public Base
{
public:
    
void bar( const Base* p )
    
{
        
this->x; // OK,因为 x 是本对象的
        p->x; // cannot access protected member,因为 x 不是本对象的
    }

}
;

阅读(2121) | 评论(12) | 转发(0) |
给主人留下些什么吧!~~

网友评论2012-11-23 16:33:40

YoYo
B::i is an example of qualified-id.

The reasons of int B::* pmi_B = &B::i; // ill-formed  is:
1) First this is an rule: except when forming a pointer to member, the protected access must be through a pointer to, reference to, or object of the derived class itself (or any class derived from that class).  But the B::i is a pointer to member, you must obey it.

2) B::i = 4; // OK (access through this, qualification ignored)

网友评论2012-11-23 16:33:33

100000
但我不知道“A pointer to member ”什么意思。
什么是“qualified-id” ?
int B::* pmi_B = &B::i; // ill-formed  
为什么不对?

网友评论2012-11-23 16:33:24

100000
精辟

网友评论2012-11-23 16:33:17

YoYo
Sorry, I write an error word "private" => "protected"

Except when forming a pointer to member(definatin bellow), the protected access must be through a pointer to, reference to, or object of the derived class itself (or any class derived from that class).  

A pointer to member is only formed when an explicit "&" is used and its operand is a qualified-id not enclosed in parentheses.

网友评论2012-11-23 16:33:08

YoYo
example from Standard:
class B {
protected:
int i;
static int j;
};
class D1 : public B {
};
class D2 : public B {
friend void fr(B*,D1*,D2*);
void mem(B*,D1*);
};

void D2::mem(B* pb, D1* p1)
{
pb->i = 1; // ill-formed
p1->i = 2; // ill-formed
i = 3; // OK (access through this)
B::i = 4; // OK (access through this, qualification ignore