如果一个函数被定义为虚函数,它究竟意味着什么?它与纯虚函数是相同的吗?


当前回答

虚方法可以被派生类覆盖,但需要基类中的实现(将要被覆盖的基类)。

纯虚方法没有基类的实现。它们需要由派生类定义。(所以从技术上讲,覆盖不是正确的术语,因为没有什么可以覆盖)。

当派生类重写基类的方法时,Virtual对应于默认的java行为。

纯虚方法对应于抽象类中的抽象方法的行为。而只包含纯虚方法和常量的类则是接口的cppp -pendant。

其他回答

“Virtual”意味着该方法可以在子类中重写,但在基类中有一个可直接调用的实现。“纯虚拟”意味着它是一个没有直接可调用实现的虚拟方法。这样的方法必须在继承层次结构中至少重写一次——如果一个类有任何未实现的虚方法,该类的对象就不能被构造,编译就会失败。

@夸克指出,纯虚拟方法可以有一个实现,但由于纯虚拟方法必须被覆盖,所以不能直接调用默认的实现。下面是一个带默认值的纯虚方法的例子:

#include <cstdio>

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

void A::Hello() {
    printf("A::Hello\n");
}

class B : public A {
public:
    void Hello() {
        printf("B::Hello\n");
        A::Hello();
    }
};

int main() {
    /* Prints:
           B::Hello
           A::Hello
    */
    B b;
    b.Hello();
    return 0;
}

根据注释,编译是否失败是特定于编译器的。至少在GCC 4.3.3中,它不会编译:

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

int main()
{
    A a;
    return 0;
}

输出:

$ g++ -c virt.cpp 
virt.cpp: In function ‘int main()’:
virt.cpp:8: error: cannot declare variable ‘a’ to be of abstract type ‘A’
virt.cpp:1: note:   because the following virtual functions are pure within ‘A’:
virt.cpp:3: note:   virtual void A::Hello()

在c++类中,virtual是一个关键字,它表示一个方法可以被子类重写(即由子类实现)。例如:

class Shape 
{
  public:
    Shape();
    virtual ~Shape();

    std::string getName() // not overridable
    {
      return m_name;
    }

    void setName( const std::string& name ) // not overridable
    {
      m_name = name;
    }

  protected:
    virtual void initShape() // overridable
    {
      setName("Generic Shape");
    }

  private:
    std::string m_name;
};

在这种情况下,子类可以覆盖initShape函数来做一些专门的工作:

class Square : public Shape
{
  public: 
    Square();
    virtual ~Square();

  protected:
    virtual void initShape() // override the Shape::initShape function
    {
      setName("Square");
    }
}

术语纯虚指的是需要由子类实现而基类还没有实现的虚函数。通过使用virtual关键字并在方法声明的末尾添加a =0,可以将一个方法指定为纯虚拟方法。

所以,如果你想让Shape::initShape纯虚拟,你会做以下事情:

class Shape 
{
 ...
    virtual void initShape() = 0; // pure virtual method
 ... 
};

通过向类中添加纯虚方法,可以使类成为抽象基类 这对于将接口与实现分离非常方便。

虚方法可以被派生类覆盖,但需要基类中的实现(将要被覆盖的基类)。

纯虚方法没有基类的实现。它们需要由派生类定义。(所以从技术上讲,覆盖不是正确的术语,因为没有什么可以覆盖)。

当派生类重写基类的方法时,Virtual对应于默认的java行为。

纯虚方法对应于抽象类中的抽象方法的行为。而只包含纯虚方法和常量的类则是接口的cppp -pendant。

Virtual functions must have a definition in base class and also in derived class but not necessary, for example ToString() or toString() function is a Virtual so you can provide your own implementation by overriding it in user-defined class(es). Virtual functions are declared and defined in normal class. Pure virtual function must be declared ending with "= 0" and it can only be declared in abstract class. An abstract class having a pure virtual function(s) cannot have a definition(s) of that pure virtual functions, so it implies that implementation must be provided in class(es) that derived from that abstract class.

虚函数是在基类中声明并由派生类重新定义的成员函数。虚函数是按继承顺序分层的。 当派生类不重写虚函数时,将使用在其基类中定义的函数。

纯虚函数是指相对于基类不包含任何定义的虚函数。 它在基类中没有实现。任何派生类都必须重写此函数。