访问派生类中的受保护成员昨天我遇到了一个错误,虽然这很容易解决,但我想确保我对C+的理解是正确的。我有一个具有受保护成员的基类:class Base{
protected:
int b;
public:
void DoSomething(const Base& that)
{
b+=that.b;
}};它编译并工作得很好。现在我扩展了Base,但仍然希望使用b:class Derived : public Base{
protected:
int d;
public:
void DoSomething(const Base& that)
{
b+=that.b;
d=0;
}};请注意,在这种情况下DoSomething仍然引用Base,不是Derived..我希望我仍然可以访问that.b在.内部Derived,但我得到了一个cannot access protected member错误(MSVC 8.0-还没有尝试GCC)。显然,在b解决了这个问题,但我想知道为什么我不能直接访问b..我认为当您使用公共继承时,受保护的变量对派生类仍然是可见的。
3 回答
![?](http://img1.sycdn.imooc.com/545861b80001d27c02200220-100-100.jpg)
慕码人2483693
TA贡献1860条经验 获得超9个赞
Derived
b
Derived
Base
Derived
![?](http://img1.sycdn.imooc.com/533e4d510001c2ad02000200-100-100.jpg)
杨魅力
TA贡献1811条经验 获得超6个赞
class Derived : public Base{ protected: int d; public: void DoSomething(const Base& that) { Base::DoSomething(that); d=0; }};
![?](http://img1.sycdn.imooc.com/533e4d660001312002000200-100-100.jpg)
白衣染霜花
TA贡献1796条经验 获得超10个赞
protected
贯通 this
指针 或相同类型的受保护成员,即使在基中声明。 或者来自朋友的课程,函数
friend
class Derived;class Base{ friend class Derived; protected: int b; public: void DoSomething(const Base& that) { b+=that.b; }};class Derived : public Base{ protected: int d; public: void DoSomething(const Base& that) { b+=that.b; d=0; }};
- 3 回答
- 0 关注
- 421 浏览
添加回答
举报
0/150
提交
取消