纯虚函数与实现 [英] pure virtual function with implementation

查看:191
本文介绍了纯虚函数与实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本的理解是,没有一个纯虚拟函数的实现,但是,我被告知可能有纯虚拟函数的实现。

  class A {
public:
virtual void f()= 0;
};

void A :: f(){
cout<<Test<< endl;
}

以上代码是否正确?



有一个纯粹的虚拟函数与一个实现的目的是什么?

解决方案

> virtual 函数必须在直接实例化的派生类型中实现,但基类型仍然可以定义实现。派生类可以通过使用完全范围的名称(通过在您的示例中调用 A :: f())显式调用基类实现(如果访问权限允许)如果 A :: f() public protected )。类似的东西:

  class B:public A {

virtual void f(){
// class B没有为f()
//做任何特殊的事情,所以我们将调用A的

//注意A的声明f be public
//或保护以避免编译时问题

A :: f();
}

};

我可以想到的我的头顶的用例是当有一个更多或者 - 不太合理的默认行为,但是类设计者希望只显式调用默认排序行为。它也可以是你想要派生类总是执行自己的工作,但也能够调用一组通用的功能的情况。



请注意,即使它是允许的通过语言,它不是我看到常用的东西(事实上,它可以做似乎让大多数C ++程序员,甚至经验丰富的人)。


My basic understanding is that there is no implementation for a pure virtual function, however, I was told there might be implementation for pure virtual function.

class A {
public:
    virtual void f() = 0;
};

void A::f() {
    cout<<"Test"<<endl;
}

Is code above OK?

What's the purpose to make it a pure virtual function with an implementation?

解决方案

A pure virtual function must be implemented in a derived type that will be directly instantiated, however the base type can still define an implementation. A derived class can explicitly call the base class implementation (if access permissions allow it) by using a fully-scoped name (by calling A::f() in your example - if A::f() were public or protected). Something like:

class B : public A {

    virtual void f() {
        // class B doesn't have anything special to do for f()
        //  so we'll call A's

        // note that A's declaration of f() would have to be public 
        //  or protected to avoid a compile time problem

        A::f();
    }

};

The use case I can think of off the top of my head is when there's a more-or-less reasonable default behavior, but the class designer wants that sort-of-default behavior be invoked only explicitly. It can also be the case what you want derived classes to always perform their own work but also be able to call a common set of functionality.

Note that even though it's permitted by the language, it's not something that I see commonly used (and the fact that it can be done seems to surprise most C++ programmers, even experienced ones).

这篇关于纯虚函数与实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆