相关疑难解决方法(0)

为什么我不能从派生类的实例访问受保护的成员?

我有一段时间没有完成C++,也无法弄清楚为什么以下不起作用:

class A {
protected:
  int num;
};

class B : public A {
};

main () {
  B * bclass = new B ();
  bclass->num = 1;
}
Run Code Online (Sandbox Code Playgroud)

编译它会产生:

错误C2248:'A :: num':无法访问在类'A'中声明的受保护成员

派生类不应该访问受保护的成员吗?

我错过了什么?

c++ inheritance

13
推荐指数
4
解决办法
3万
查看次数

为什么我们不能从派生类中调用受保护的析构函数?

我知道私有(当然还有公共)析构函数的用法.

我也知道在派生类中使用受保护的析构函数:

使用受保护的析构函数来防止通过基类指针销毁派生对象

但我已经尝试运行以下代码,它将无法编译:

struct A{
    int i;
    A() { i = 0;}
    protected: ~A(){}
};

struct B: public A{
    A* a;
    B(){ a = new A();}
    void f(){ delete a; }
};


int main()
{
   B b= B();
   b.f();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

void B::f()':
main.cpp:9:16: error: 'A::~A()' is protected
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

如果我从f()内部调用A中的受保护方法,它将起作用.那么为什么叫d tor不同呢?

c++ oop inheritance destructor c++11

9
推荐指数
1
解决办法
1643
查看次数

无法调用基类保护函数?

我不能在我的基类中调用protected函数.为什么?它看起来像这样:

class B : B2
{
public:
  virtual f1(B*)=0;
protected:
  virtual f2(B*) { codehere(); }
}
class D : public B
{
public:
  virtual f1(B*b) { return f2(b); }
protected:
  virtual f2(B*b) { return b->f2(this); }
}
Run Code Online (Sandbox Code Playgroud)

在msvc中我得到错误错误C2248:'name :: class :: f2':无法访问类'name :: class'中声明的受保护成员

在gcc中我得到错误:'virtual int name :: class :: f2()'受到保护.

这是为什么?我认为受保护成员的要点是派生类调用.

c++ inheritance

7
推荐指数
1
解决办法
6197
查看次数

标签 统计

c++ ×3

inheritance ×3

c++11 ×1

destructor ×1

oop ×1