继承的典型问题

发布于 2024-09-18 23:05:09 字数 1095 浏览 9 评论 0原文

可能的重复:
为什么在 C++ 中不允许这样做?

为什么会这样C++ 中不允许...??

class base
{
  private:

  public:
      void func()
         {
              cout<<"base";
         }  


};

class derived : private base
{
  private:


  public:
            void func()
         {
              cout<<"derived";
              }


};

int main()
{
base * ptr;
ptr = new derived;
((derived *)ptr)->func();
return 0;
}

我收到错误

**61 C:\Dev-Cpp\My Projects\pointertest.cpp `base' is an inaccessible base of `derived'** 

我的问题是,由于 func() 在派生类中定义了 public 且语句 ((派生 *)ptr)->func();正在尝试显示派生的 func() ..为什么由于继承模式而存在可访问问题..虽然我已经有了公共派生函数,但继承模式(私有)如何影响调用() 在派生类中..?

如果继承模式更改为公共,我会得到我想要的结果..但是 func() 在基类中是私有的(因此基类的 func() 不会被继承)并且 func() 在派生模式中是公共的继承是公共为什么我仍然得到我想要的结果..我应该像前面的情况一样收到编译错误吗?

我完全困惑了..请告诉我编译器在这种情况下是如何工作的..??

Possible Duplicate:
Why is this not allowed in C++?

Why is this not allowed in C++...??

class base
{
  private:

  public:
      void func()
         {
              cout<<"base";
         }  


};

class derived : private base
{
  private:


  public:
            void func()
         {
              cout<<"derived";
              }


};

int main()
{
base * ptr;
ptr = new derived;
((derived *)ptr)->func();
return 0;
}

I am getting an error

**61 C:\Dev-Cpp\My Projects\pointertest.cpp `base' is an inaccessible base of `derived'** 

My question is that since func() is defined public in derived class and the statement
((derived *)ptr)->func(); is trying to display the func() of derived..Why is there an accessible issue due to mode of inheritance..How does mode of inheritance(private) affects the call although I already have public derived func() in derived class..?

If mode of inheritance is changed to public I get my desired result..But a case where func() is private in base(so as func() of base is not inherited) and also func() is public in derived and mode of inheritance is public why still am I getting my desired result..Shouldn I be getting an Compile error as in the previous case ??

I am totally confused ..Please tell me how the compiler works in this case..??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌︼了一个春 2024-09-25 23:05:09

当存在私有继承时,不能让基指针指向派生对象。

公共继承表达了一种isa关系。另一方面,私有继承表示根据关系实现

编译错误指的是以下行:
ptr = 新派生;

You can't let the base pointer point to the derived object when there is private inheritance.

Public inheritance expresses an isa relationship. Private inheritance on the other hand expresses a implemented in terms of relationship

Ther compile error refers to the line:
ptr = new derived;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文