Declaring functions
|
|
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
You can help to correct and verify the translation. Click here for instructions.
ret name ( params ) ;
|
(1) | ||||||||
ret name ( params ) cv ref except attr ;
|
(2) | ||||||||
auto name ( params ) cv ref except attr -> ret ;
|
(3) | (начиная с C++11) | |||||||
You can help to correct and verify the translation. Click here for instructions.
decl name ( params ) { body }
|
(4) | ||||||||
attr decl name ( params ) cv ref except attr virt try init-list { body } catch
|
(5) | ||||||||
attr decl name ( params ) cv ref except attr -> ret virt try init-list { body } catch
|
(6) | (начиная с C++11) | |||||||
attr decl name ( params ) cv ref except attr virt = 0 ;
|
(7) | ||||||||
attr decl name ( params ) cv ref except attr virt = default ;
|
(8) | (начиная с C++11) | |||||||
attr decl name ( params ) cv ref except attr virt = delete ;
|
(9) | (начиная с C++11) | |||||||
[править] Объяснение
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
| attr(C++11) | - | Дополнительно последовательность из любого количества Функция атрибутов, таких как [[noreturn]] или [[carries_dependency]]. Может появиться как до, так и после имени функции
Original: Optional sequence of any number of Функция атрибутов, such as [[noreturn]] or [[carries_dependency]]. May appear both before and after the function name The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||
| ret | - | Тип, возвращаемый функцией, может быть void если функция ничего не возвращает. Не может быть массив или функцию типа, хотя может быть указатель или ссылка на таковую. Обязательный для всех функций, кроме конструкторов, деструкторы и операторы преобразования, которые не должны обеспечить возврат типа .
Original: the type returned by the function, may be void if the function returns nothing. Cannot be array or function type, although can be a pointer or reference to such. Required for all functions except constructors, destructors, and conversion operators, which must not provide a return type. The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||
| decl | - | Декларация спецификатор последовательность, которая состоит ни одного или некоторых из следующих ключевых слов: статических, внешний, встроенный, virtual, explicit, friend, КонстВыраж, в сочетании с типом возвращаемого значения, ret
Original: declaration specifier sequence, which consists of none or some of the following keywords: статических, внешний, встроенный, virtual, explicit, friend, КонстВыраж, combined with the return type, ret The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. {{param list item | cv |{{tr| Дополнительно const, volatile, или const volatile, применимо только к не-статические функции-члены. Для функции-члена класса | ||||
| ref(C++11) | - | Дополнительно & или &&, применимо только к нестатические функции-члены, кроме конструкторов и деструкторов. Для члена функции
T класса, типа неявного параметра объекта с целью разрешения перегрузки будет T& или T&& соответственно: && квалифицированный член функции может быть вызван только для выражения объекта RValueOriginal: Optional & or &&, only applicable to non-static member functions other than constructors or destructors. For a member function of class T, the type of the implicit object parameter for the purpose of overload resolution will be T& or T&& respectively: a &&-qualified member function can only be called on an rvalue object expressionThe text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||
| except | - | либо динамического исключения спецификации или noexcept-спецификации
Original: The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||
| virt(C++11) | - | Дополнительно override или final, применимо только к не-статические функции-члены
Original: Optional override or final, only applicable to non-static member functions The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||
->ret(C++11)
|
- | Трейлинг возвращаемого типа, применяется только в случае ret является auto. Полезно, если тип зависит от аргументов имена, такие как template <class T, class U> auto add(T t, U u) -> decltype(t + u); или сложные, например, в auto fpif(int)->int(*)(int)
Original: Trailing return type, only applicable if ret is auto. Useful if the type depends on argument names, such as template <class T, class U> auto add(T t, U u) -> decltype(t + u); or is complicated, such as in auto fpif(int)->int(*)(int) The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||
| init-list | - | Список инициализации конструктора, используется только в конструкторах
Original: Список инициализации конструктора, only used in constructors The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||
try
|
- | Дополнительный блок попытки функции. Если они присутствуют, catch должны быть обеспечены
Original: Optional function try block. If present, catch must be provided The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||
| catch | - | Дополнительно последовательность поймать-блоки, применимо только из
try используется . Original: Optional sequence of поймать-блоки, only applicable of try is used. The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||
| body | - | В теле функции (возможно, пустой) составного оператора
Original: The body of the function, a (possibly empty) compound statement The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. | ||||
| params | - | Список
Original: The list of parameters
The text has been machine-translated via Google Translate. You can help to correct and verify the translation. Click here for instructions. |
[править] Пример 1: не являющегося членом функции
#include <iostream> #include <string> // declaration in namespace(file) scope // (the definition is provided later) int f1(); // simple function with a default argument, returning nothing void f0(const std::string& arg = "world") { std::cout << "Hello, " << arg << '\n'; } // function returning a pointer to f0 auto fp11() -> void(*)(const std::string&) { return f0; } // function returning a pointer to f0, pre-C++11 style void (*fp03())(const std::string&) { return f0; } int main() { f0(); fp11()("test"); fp03()("again"); int f2(std::string); // declaration in function scope std::cout << f2("bad12") << '\n'; } // simple non-member function returning int int f1() { return 42; } // function with an exception specification and a function try block int f2(std::string str) noexcept try { return std::stoi(str); } catch(const std::exception& e) { std::cerr << "stoi() failed!\n"; return 0; }
Вывод:
Hello, world Hello, test Hello, again stoi() failed! 0
[править] Пример 2: функции-члены
#include <iostream> #include <string> #include <utility> #include <exception> struct S { int data; // simple converting constructor (declaration) S(int val); // simple explicit constructor (declaration) explicit S(std::string str); // const member function (definition) virtual int getData() const { return data; } }; // definition of the constructor S::S(int val) : data(val) { std::cout << "ctor1 called, data = " << data << '\n'; } // this constructor has a catch clause S::S(std::string str) try : data(std::stoi(str)) { std::cout << "ctor2 called, data = " << data << '\n'; } catch(const std::exception&) { std::cout << "ctor2 failed, string was '" << str << "'\n"; throw; // ctor's catch clause should always rethrow } struct D : S { int data2; // constructor with a default argument D(int v1, int v2 = 11) : S(v1), data2(v2) {} // virtual member function int getData() const override { return data*data2; } // lvalue-only assignment operator D& operator=(D other) & { std::swap(other.data, data); std::swap(other.data2, data2); return *this; } }; int main() { D d1 = 1; S s2("2"); try { S s3("not a number"); } catch(const std::exception&) {} std::cout << s2.getData() << '\n'; D d2(3, 4); d2 = d1; // OK: assignment to lvalue // D(5) = d1; // ERROR: no suitable overload of operator= }
Вывод:
ctor1 called, data = 1 ctor2 called, data = 2 ctor2 failed, string was 'not a number' 2 ctor1 called, data = 3