Пространства имён
Варианты
Действия

virtual function specifier

Материал из cppreference.com

 
 
Язык С++
Общие темы
Управление программой
Операторы условного выполнения
Операторы повторения
Операторы перехода
Функции
объявление функции
объявление лямбда-функции
шаблон функции
спецификатор inline
спецификаторы исключений (устарело)
спецификатор noexcept (C++11)
Исключения
Пространства имён
объявление пространства имён
псевдонимы пространства имён
Типы
спецификатор decltype (C++11)
Спецификаторы
cv-спецификаторы
спецификаторы продолжительности хранения
спецификатор constexpr (C++11)
спецификатор auto (C++11)
спецификатор alignas (C++11)
Инициализация
Литералы
Выражения
Утилиты
Типы
typedef-объявление
объявление псевдонима типа (C++11)
атрибуты (C++11)
Приведения типов
неявные преобразования
const_cast-преобразование
static_cast-преобразование
dynamic_cast-преобразование
reinterpret_cast-преобразование
C-подобное и функциональное приведение типов
Выделение памяти
Классы
Особые свойства классовых функций
виртуальная функция
спецификатор override (C++11)
спецификатор final (C++11)
Специальные функции-члены
Шаблоны
шаблон класса
шаблон функции
специализация шаблона
упакованные параметры (C++11)
Разное
Ассемблерные вставки
 
Указывает, что функция является виртуальной
Original:
Specifies that a function is virtual
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Содержание

[править] Синтаксис

virtual function_declaration ;

[править] Объяснение

Виртуальные функции являются функциями-членами, чье поведение может быть переопределен в производных классах. В отличие от не виртуальные функции, переопределить поведение сохраняется, даже если нет времени компиляции информации о фактическом тип класса. Это означает, что, даже если производный класс обрабатываются с помощью указателя или ссылки на базовый класс, вызов переопределить виртуальную функцию будет вызывать поведение, определенные в производном классе.
Original:
Virtual functions are member functions whose behavior can be overridden in derived classes. As opposed to non-virtual functions, the overridden behavior is preserved even if there is no compile-time information about the actual type of the class. That means, even if a derived class is handled using pointer or reference to the base class, a call to a overridden virtual function would invoke the behavior defined in the derived class.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Функция подписи должны быть одинаковыми для того, чтобы быть переопределены.
Original:
The function signature must be the same in order to be overridden.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Возвращаемый тип главной виртуальной функции не обязательно должны быть идентичны переопределить функцию. Типы могут быть различными, если они являются' ковариантный друг с другом. Два типа ковариантны, если они удовлетворяют следующим требованиям:
Original:
The return type of a overriding virtual function doesn't necessarily need to be the identical to that of the overridden function. The types can be different if they are covariant with each another. Two types are covariant if they satisfy the following requirements:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Здесь мы ссылаемся на главной функцией, как Derived::f() и переопределить функцию Base::f()
Original:
Here we refer to the overriding function as Derived::f() and to the overridden function as Base::f()
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • обоих типов указателей или ссылок на классы. Многоуровневая указатели или ссылки не допускаются.
    Original:
    both types are pointers or references to classes. Multi-level pointers or references are not allowed.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • класс возвращаемого типа Base::f() должны быть однозначными и доступными прямых или косвенных базовых классов класса типа возвращаемого Derived::f().
    Original:
    the class of the return type of Base::f() must be a unambiguous and accessible direct or indirect base class of the class of the return type of Derived::f().
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • возвращаемого типа Derived::f() должны быть одинаково или меньше, чем CV-квалификацию возвращаемого типа Base::f().
    Original:
    the return type of Derived::f() must be equally or less CV-квалификацию than the return type of Base::f().
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Если виртуальная функция вызывается непосредственно, то есть, явно квалификационный класс он является членом, то механизм вызова виртуальной подавляется, и что конкретная реализация называется.
Original:
If a virtual function is called directly, that is, explicitly qualifying the class it is a member of, then the virtual call mechanism is suppressed and that particular implementation is called.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Виртуальный деструктор базового класса всегда переопределить деструктор производного класса, несмотря на то что деструкторы не наследуются иначе.
Original:
A virtual destructor of a base class is always overridden by a destructor of a derived class, even though that destructors are otherwise not inherited.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Правила доступа к виртуальной функции определяются первой декларации. Доступ правилам, определенным заявлениям главной функции распространяется только на прямые вызовы функций.
Original:
The access rules to a virtual function are determined by the first declaration. Access rules defined by the declarations of the overriding functions apply only to the direct function calls.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
virtual функции спецификатор предполагает членства, таким образом, единственным членом функции могут быть виртуальными. Кроме того, поскольку экземпляр класса необходима для того, чтобы вызвать виртуальную функцию, виртуальная функция не может быть static.
Original:
virtual function specifier implies membership, thus only member functions can be virtual. Also, since an instance of a class is needed in order to call a virtual function, virtual function can not be static.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Функции шаблоны не могут быть объявлены virtual. Это относится только к функциям, которые сами шаблоны - регулярные функции-члена шаблона класса может быть объявлен виртуальным.
Original:
Functions templates cannot be declared virtual. This applies only to functions that are themselves templates - a regular member function of a class template can be declared virtual.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[править] Пример

class Parent {
public:
    void functionA();
    virtual void functionB();   //Note the keyword virtual
    void functionC();
};
 
class Child : public Parent {
public:
    void functionA();
    virtual void functionB();   //Note the keyword virtual
};
 
int main()
{
    Parent* p1 = new Parent;
    Parent* p2 = new Child;
    Child* c = new Child;
 
    p1->functionA();   //Calls Parent::functionA
    p1->functionB();   //Calls Parent::functionB
    p1->functionC();   //Calls Parent::functionC
 
    p2->functionA();   //Calls Parent::functionA because p2 points to a Parent
    p2->functionB();   //Calls Child::functionB even though p2 points
                       // to a Parent because functionB is virtual
    p2->functionC();   //Calls Parent::functionC
 
    c->functionA();   //Calls Child::functionA
    c->functionB();   //Calls Child::functionB
    c->functionC();   //Calls Parent::functionC
 
    return 0;
}


[править] См. также