私有继承:如何创建基类的对象(具有纯虚方法)?

发布于 2024-11-16 07:54:21 字数 417 浏览 3 评论 0原文

考虑以下代码:

class Base
{
  protected:
  virtual void methodDefinedInBase() = 0;
}

Class Derived: private Base
{
  public:
  void someMethod();
  protected:
  virtual void methodDefinedInBase()
  {
    std::cout<<"From B"<<std::endl;
  }
}

在上面的代码中,我可以创建“Derived”类型的对象。 C++ 允许我从派生类中的“someMethod()”访问方法“methodDefinedInBase()”。但是,如何创建“Base”类型的对象?

谢谢,

毗湿奴。

Consider the following code:

class Base
{
  protected:
  virtual void methodDefinedInBase() = 0;
}

Class Derived: private Base
{
  public:
  void someMethod();
  protected:
  virtual void methodDefinedInBase()
  {
    std::cout<<"From B"<<std::endl;
  }
}

In the above code, I can create object of type "Derived". C++ allows me access to the method "methodDefinedInBase()" from "someMethod()" in Derived class. But, how do I create an object of type "Base" ?

Thanks,

Vishnu.

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

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

发布评论

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

评论(3

触ぅ动初心 2024-11-23 07:54:21

正如 Beta 在评论中指出的那样,您无法实例化抽象基类(具有纯虚方法的基类)。您只能实例化实现这些纯虚方法的派生类。无论您使用的是公共继承还是私有继承,都是如此。

As Beta noted in a comment, you can't instantiate an abstract base class (one with pure virtual methods.) You can only instantiate derived classes that implement those pure virtual methods. That's true regardless of whether you're using public or private inheritance.

嘿看小鸭子会跑 2024-11-23 07:54:21

您不创建任何“Base”类型的对象——通过为 Base 提供一个纯虚拟成员,您明确表示该类不能单独存在,而只能通过派生类存在。您想要创建的是指向 Base 的指针引用

Derived1 x;
Derived2 y;

// Somewhere inside Derived1:
Base & rb = x;

// Somewhere inside Derived2:
Base * pb = &y;

然后您可以通过处理 rbpb 来使用多态性> 统一,无需知道xy的具体类型。

You don't create any objects of type "Base" -- by giving Base a pure-virtual member, you are explicitly saying that this class cannot exist by itself, but only through derived classes. What you do want to create are pointers or references to Base:

Derived1 x;
Derived2 y;

// Somewhere inside Derived1:
Base & rb = x;

// Somewhere inside Derived2:
Base * pb = &y;

Then you can use polymorphism by treating rb and pb uniformly without needing to know the concrete type of x and y.

傲娇萝莉攻 2024-11-23 07:54:21

在基类中声明纯虚函数意味着: 1. 该类的对象不能被实例化。 2. 要实例化派生类的对象,必须定义所有纯虚函数。换句话说,纯虚方法不允许您创建定义的类的对象。

Declaration of pure virtual function in a base class means: 1. Object of such class can not be instantiated. 2. To instantiate object of derived class all pure virtual functions must be defined. In other words pure virtual method disallow you to create object of class where one defined.

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