继承c++类型保护
inheritance C++ type protected
我在继承(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();
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- C2011: 'Card':"类"类型重新定义(尽管使用了包含保护并且没有在文件中重新定义.cpp类)
- 在带有类型保护的模板文件中使用前向声明
- 同一模板类但模板类型的受保护成员
- 受保护的嵌套结构不能用作派生外部类中的返回类型?
- 在 lambda 函数 g++-4.8 中调用继承的受保护子类型
- 无法从派生类型的作用域访问另一个实例的受保护成员
- C :可以从类及其受保护的成员类型继承可以继承吗?
- 如何按类型启用受保护的方法
- 受保护的枚举不被视为类型,为什么?
- 类型重定义错误(使用标头保护)
- 在派生类中定义自定义返回类型的受保护方法
- 如果继承类型受到保护,我可以制作基类的指针以指向派生对象吗?
- 访问超类类型成员对象的受保护成员 - 一个优雅的解决方案
- 类型检查受保护的标记联合
- 继承c++类型保护
- C++中受保护的类型