我正在学习C++,我刚刚开始学习虚拟函数。

从我(在书中和网上)读到的内容来看,虚拟函数是基类中的函数,可以在派生类中重写。

但在本书的早些时候,当我学习基本继承时,我能够在派生类中重写基函数,而不使用虚函数。

那么我在这里错过了什么?我知道虚拟函数还有很多,它似乎很重要,所以我想清楚它到底是什么。我只是在网上找不到一个直截了当的答案。


当前回答

如果你知道潜在的机制,这会有所帮助。C++将C程序员使用的一些编码技术形式化,用“覆盖”代替“类”-具有公共头段的结构将用于处理不同类型的对象,但具有一些公共数据或操作。通常,覆盖的基本结构(公共部分)具有指向函数表的指针,该函数表指向每个对象类型的不同例程集。C++做了同样的事情,但隐藏了机制,即C++ptr->func(…),其中func是C的虚拟(*ptr->func_table[func_num])(ptr,…),派生类之间的变化是func_table内容。[非虚拟方法ptr->func()仅转换为mangled_func(ptr,..)。]

这样做的结果是,您只需要了解基类就可以调用派生类的方法,即,如果例程了解类a,您可以向它传递派生类B指针,那么所调用的虚拟方法将是B的虚拟方法,而不是a的虚拟方法。

其他回答

底线是,虚拟功能使生活更轻松。让我们使用M Perry的一些想法,并描述如果我们没有虚拟函数而只能使用成员函数指针会发生什么。在没有虚函数的正常估计中,我们有:

 class base {
 public:
 void helloWorld() { std::cout << "Hello World!"; }
  };

 class derived: public base {
 public:
 void helloWorld() { std::cout << "Greetings World!"; }
 };

 int main () {
      base hwOne;
      derived hwTwo = new derived();
      base->helloWorld(); //prints "Hello World!"
      derived->helloWorld(); //prints "Hello World!"

好的,这就是我们所知道的。现在让我们尝试使用成员函数指针:

 #include <iostream>
 using namespace std;

 class base {
 public:
 void helloWorld() { std::cout << "Hello World!"; }
 };

 class derived : public base {
 public:
 void displayHWDerived(void(derived::*hwbase)()) { (this->*hwbase)(); }
 void(derived::*hwBase)();
 void helloWorld() { std::cout << "Greetings World!"; }
 };

 int main()
 {
 base* b = new base(); //Create base object
 b->helloWorld(); // Hello World!
 void(derived::*hwBase)() = &derived::helloWorld; //create derived member 
 function pointer to base function
 derived* d = new derived(); //Create derived object. 
 d->displayHWDerived(hwBase); //Greetings World!

 char ch;
 cin >> ch;
 }

虽然我们可以用成员函数指针做一些事情,但它们不如虚拟函数灵活。在类中使用成员函数指针是很棘手的;至少在我的实践中,成员函数指针几乎总是必须在主函数中或从成员函数中调用,如上面的示例所示。

另一方面,虚拟函数虽然可能有一些函数指针开销,但确实大大简化了事情。

EDIT:还有一种方法与eddietree类似:c++虚拟函数与成员函数指针(性能比较)。

您需要虚拟方法来实现安全的下变频、简单和简洁。

这就是虚拟方法所做的:它们安全地向下转换,使用明显简单而简洁的代码,避免了在更复杂和冗长的代码中进行不安全的手动转换。


Non-virtual method ⇒ static binding ========================================

以下代码故意“不正确”。它没有将value方法声明为virtual,因此会产生意外的“错误”结果,即0:

#include <iostream>
using namespace std;

class Expression
{
public:
    auto value() const
        -> double
    { return 0.0; }         // This should never be invoked, really.
};

class Number
    : public Expression
{
private:
    double  number_;
    
public:
    auto value() const
        -> double
    { return number_; }     // This is OK.

    Number( double const number )
        : Expression()
        , number_( number )
    {}
};

class Sum
    : public Expression
{
private:
    Expression const*   a_;
    Expression const*   b_;
    
public:
    auto value() const
        -> double
    { return a_->value() + b_->value(); }       // Uhm, bad! Very bad!

    Sum( Expression const* const a, Expression const* const b )
        : Expression()
        , a_( a )
        , b_( b )
    {}
};

auto main() -> int
{
    Number const    a( 3.14 );
    Number const    b( 2.72 );
    Number const    c( 1.0 );

    Sum const       sum_ab( &a, &b );
    Sum const       sum( &sum_ab, &c );
    
    cout << sum.value() << endl;
}

在注释为“坏”的行中,调用了Expression::value方法,因为静态已知类型(编译时已知的类型)是Expression,而value方法不是虚拟的。


Virtual method ⇒ dynamic binding. ======================================

在静态已知类型表达式中将值声明为virtual可确保每次调用都会检查这是什么实际类型的对象,并调用该动态类型的值的相关实现:

#include <iostream>
using namespace std;

class Expression
{
public:
    virtual
    auto value() const -> double
        = 0;
};

class Number
    : public Expression
{
private:
    double  number_;
    
public:
    auto value() const -> double
        override
    { return number_; }

    Number( double const number )
        : Expression()
        , number_( number )
    {}
};

class Sum
    : public Expression
{
private:
    Expression const*   a_;
    Expression const*   b_;
    
public:
    auto value() const -> double
        override
    { return a_->value() + b_->value(); }    // Dynamic binding, OK!

    Sum( Expression const* const a, Expression const* const b )
        : Expression()
        , a_( a )
        , b_( b )
    {}
};

auto main() -> int
{
    Number const    a( 3.14 );
    Number const    b( 2.72 );
    Number const    c( 1.0 );

    Sum const       sum_ab( &a, &b );
    Sum const       sum( &sum_ab, &c );
    
    cout << sum.value() << endl;
}

这里的输出应该是6.86,因为虚拟方法是虚拟调用的。这也称为调用的动态绑定。执行一点检查,找到对象的实际动态类型,并调用该动态类型的相关方法实现。

相关的实现是最特定(最派生)类中的实现。

注意,这里的派生类中的方法实现没有标记为virtual,而是标记为override。它们可以被标记为虚拟,但它们是自动虚拟的。override关键字确保如果某个基类中没有这样的虚拟方法,那么您将得到一个错误(这是可取的)。


The ugliness of doing this without virtual methods ==================================================

如果没有虚拟绑定,则必须实现一些自己动手版本的动态绑定。这通常涉及不安全的手动降级、复杂性和冗长。

对于单个函数的情况,如这里所示,将函数指针存储在对象中并通过该函数指针进行调用就足够了,但即使如此,它也会涉及一些不安全的下变频、复杂性和冗长性,即:

#include <iostream>
using namespace std;

class Expression
{
protected:
    typedef auto Value_func( Expression const* ) -> double;

    Value_func* value_func_;

public:
    auto value() const
        -> double
    { return value_func_( this ); }
    
    Expression(): value_func_( nullptr ) {}     // Like a pure virtual.
};

class Number
    : public Expression
{
private:
    double  number_;
    
    static
    auto specific_value_func( Expression const* expr )
        -> double
    { return static_cast<Number const*>( expr )->number_; }

public:
    Number( double const number )
        : Expression()
        , number_( number )
    { value_func_ = &Number::specific_value_func; }
};

class Sum
    : public Expression
{
private:
    Expression const*   a_;
    Expression const*   b_;
    
    static
    auto specific_value_func( Expression const* expr )
        -> double
    {
        auto const p_self  = static_cast<Sum const*>( expr );
        return p_self->a_->value() + p_self->b_->value();
    }

public:
    Sum( Expression const* const a, Expression const* const b )
        : Expression()
        , a_( a )
        , b_( b )
    { value_func_ = &Sum::specific_value_func; }
};


auto main() -> int
{
    Number const    a( 3.14 );
    Number const    b( 2.72 );
    Number const    c( 1.0 );

    Sum const       sum_ab( &a, &b );
    Sum const       sum( &sum_ab, &c );
    
    cout << sum.value() << endl;
}

看待这一点的一种积极方式是,如果您遇到了如上所述的不安全的下变频、复杂性和冗长,那么通常一个或多个虚拟方法确实会有帮助。

您必须区分重写和重载。如果没有virtual关键字,则只能重载基类的方法。这只意味着隐藏。假设您有一个基类base和一个派生类Specialized,它们都实现了void foo()。现在有一个指向Base的指针指向Specialized的实例。当您对其调用foo()时,您可以观察到virtual的不同之处:如果该方法是虚拟的,则将使用Specialized的实现,如果缺少,则将选择Base的版本。最好不要重载基类中的方法。使方法非虚拟化是作者告诉你它在子类中的扩展不是有意的。

我们需要支持“运行时多态性”的虚拟方法。当使用指针或对基类的引用引用派生类对象时,可以为该对象调用虚拟函数并执行派生类版本的函数。

跟进@user6359267的回答,C++范围层次结构是

global -> namespace -> class -> local -> statement

因此,每个类都定义了一个范围。如果不是这样的话,子类中的重写函数实际上会在同一范围内重新定义函数,而链接器不允许这样做:

在每个翻译单元中使用之前必须声明函数,并且一个函数只能在整个程序(跨所有翻译单元)的给定范围内定义一次

由于每个类都定义了自己的作用域,因此被调用的函数是在调用该函数的对象的类中定义的函数。所以

#include <iostream>
#include <string>

class Parent
{
public:
    std::string GetName() { return "Parent"; }
};

class Child : public Parent
{
public:
    std:::string GetName() { return "Child"; }
};

int main()
{
    Parent* parent = new Parent();
    std::cout << parent->GetName() << std::endl;

    Child* child = new Child();
    std::cout << child->GetName() << std::endl;

    *parent = child;
    std::cout << child->GetName() << std::endl;

    return 0;
}

输出

Parent
Child
Parent

因此,我们需要一种方法来告诉编译器应该在运行时而不是编译时确定要调用的函数。这就是虚拟关键字的作用。

这就是为什么函数重载被称为编译时多态(或早期绑定),而虚拟函数重写被称为运行时多态(或者后期绑定)。

细节:

在内部,当编译器看到一个虚拟函数时,它会创建一个类成员指针,该指针使用.*和->*运算符一般指向该类的成员(而不是对象中该成员的特定实例)。他们的工作是允许您访问一个类的成员,该成员具有指向该成员的指针。这些很少被程序员直接使用(也许除非你正在编写一个编译器来实现“虚拟”)。