私有继承:如何创建基类的对象(具有纯虚方法)?
考虑以下代码:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 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.
您不创建任何“Base”类型的对象——通过为 Base 提供一个纯虚拟成员,您明确表示该类不能单独存在,而只能通过派生类存在。您想要创建的是指向 Base 的指针或引用:
然后您可以通过处理
rb
和pb
来使用多态性> 统一,无需知道x
和y
的具体类型。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:
Then you can use polymorphism by treating
rb
andpb
uniformly without needing to know the concrete type ofx
andy
.在基类中声明纯虚函数意味着: 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.