继承c++类型保护

inheritance C++ type protected

本文关键字:保护 类型 c++ 继承      更新时间:2023-10-16

我在继承(c++)下面得到这个错误:

B.cpp:11:9: error: 'isMember' is a protected member of 'A'
   if(x->isMember())

我已经看到,在"母"类中声明的受保护成员可以从"子"类的成员访问。但我还是不知道问题出在哪里。下面是我的两个类A和B的定义:

#ifndef _A_H_
#define _A_H_
class A 
{
  private:
  bool _member;
  public:
  A();
  virtual ~A();
  protected:
  bool isMember();
   };
#endif // _A_H_
//A.cpp
#include "A.h"
A::A(){_member=true;}
A::~A(){};
bool A::isMember()
{
    return _member;
}
//B.h
#ifndef _B_H_
#define _B_H_
#include "A.h"
class B : public A 
{
 private:
    A * _memberB;
public:
  B( A *x);
  ~B();
};
#endif // _B_H_
//B.cpp
#include "B.h"
#include "A.h"
B::B(A * x)
{
    if(x->isMember()) // call of the protected member of class A
    this->_memberB=x;  
}
B::~B()
{
    //cout<<"B--"<<endl;
    delete this->_memberB;  
}
//main.cpp
#include "B.h"
int main()
{
  A * a=  new A();
  B * b= new B(a);
    return 0;
}

在c++中是按类而不是按对象来保护的

逐对象式:
你不能通过子对象从外部访问父类的受保护成员,即使子对象实际上可以访问父类的受保护函数:

Child c;
c.protectedFunction(); // wont work, because you are calling protectedFunction() outside the child object.

每个类
但是你可以通过子类访问它:

class Child : public Parent
{
    public: 
        void someFunction()
        {
            protectedParentFunction(); // it works! you are callign it from Child class
        }
}

要解决这个问题,你应该在Child类中编写一个公共函数,从Parent类中调用受保护的函数。

class Child : public Parent
{
    public: 
        void callerOfProtectedFunction()
        {
            protectedParentFunction();
        }
}
Child c;
c.callerOfProtectedFunction();