Espacios de nombres
Variantes
Acciones

Declaring functions

De cppreference.com
< cpp‎ | language

 
 
Lenguaje C++
Los temas generales
Original:
General topics
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Control de flujo
Original:
Flow control
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Sentencias condicionales ejecución
Original:
Conditional execution statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Instrucciones de iteración
Original:
Iteration statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Ir declaraciones
Original:
Jump statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funciones
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaración de la función
lambda declaración de la función
función de plantilla
especificador inline
especificaciones de excepción (obsoleto)
noexcept especificador (C++11)
Excepciones
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los espacios de nombres
Original:
Namespaces
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
tipos de unión
tipos de funciones
decltype specifier (C++11)
Los especificadores
Original:
Specifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
cv especificadores
almacenamiento duración especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialización
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los literales
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expresiones
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representaciones alternativas
Utilidades
Original:
Utilities
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
typedef declaration
alias de tipo de declaración (C++11)
atributos (C++11)
Lanza
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversiones implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-cast estilo y funcional
De asignación de memoria
Original:
Memory allocation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Clases
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Clase propiedades específicas de la función
Original:
Class-specific function properties
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funciones especiales miembro
Original:
Special member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Plantillas
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
clase de plantilla
función de plantilla
plantilla de especialización
paquetes de parámetros (C++11)
Varios
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Montaje en línea
 
Una declaración de función se introduce el nombre de la función y su tipo. Puede aparecer en cualquier ámbito, y que comúnmente se colocan en los archivos de cabecera .
Original:
A function declaration introduces the function name and its type. It may appear in any scope, and is commonly placed in header files.
The text has been machine-translated via Google Translate.
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) (desde C++11)
Una definición de función proporciona el cuerpo de una función. Sólo puede aparecer en espacio de nombres o ámbito de la clase .
Original:
A function definition provides the body of a function. It may only appear in namespace or class scope.
The text has been machine-translated via Google Translate.
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) (desde C++11)
attr decl name ( params ) cv ref except attr virt = 0 ; (7)
attr decl name ( params ) cv ref except attr virt = default ; (8) (desde C++11)
attr decl name ( params ) cv ref except attr virt = delete ; (9) (desde C++11)

[editar] Explicación

1)
Declaración de la función típica
Original:
Typical function declaration
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
Declaración de la función integral
Original:
Comprehensive function declaration
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
Declaración de la función completa con el tipo de cambio al final
Original:
Comprehensive function declaration with trailing return type
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
4)
Típico función no miembro definición
Original:
Typical non-member function definition
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
5)
Definición de la función integral
Original:
Comprehensive function definition
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
6)
Definición de función completa con el tipo de cambio al final
Original:
Comprehensive function definition with trailing return type
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
7)
Función miembro virtual pura
Original:
Pure virtual member function
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
8)
Función miembro Fallidos
Original:
Defaulted member function
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
9)
Suprimido función miembro
Original:
Deleted member function
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
attr(C++11) -
Secuencia opcional de cualquier número de atributos funcionales, tales como [[noreturn]] o [[carries_dependency]]. Puede aparecer tanto antes como después de que el nombre de la función
Original:
Optional sequence of any number of atributos funcionales, 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 -
el tipo devuelto por la función, puede ser void si la función no devuelve nada. No puede ser amplia o tipo de función, aunque puede ser un puntero o referencia a los mismos. Se requiere para todas las funciones excepto constructores, destructores y operadores de conversión, que no deben proporcionar un tipo de retorno .
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 -
declaración secuencia especificador, que consta de ninguno o algunos de los siguientes palabras clave: extern estático,, inline, virtual, explicit, friend, constexpr, combinado con el tipo de retorno, ret
Original:
declaration specifier sequence, which consists of none or some of the following keywords: extern estático,, inline, virtual, explicit, friend, constexpr, 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.

{{par | cv |{{tr| Opcional const, volatile o const volatile, sólo es aplicable a las funciones miembro no estáticas. Para una función miembro de clase T, el tipo de la [[cpp / idioma / este| Optional const, volatile, or const volatile, only applicable to non-static member functions. For a member function of class T, the type of the [[cpp/language/this}}|this pointer]] will be const T*, volatile T*, or const volatile T* respectively. A member function declared const cannot modify members of *this.}}

ref(C++11) -
Opcional & o &&, sólo es aplicable a las funciones miembro no estáticas que no sean constructores o destructores. Para una función miembro de T clase, el tipo del parámetro objeto implícito el propósito de la resolución de sobrecarga será T& o T&& respectivamente: una función miembro && cualificado sólo se puede llamar en una expresión de objeto rvalue
Original:
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 expression
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
except -
ya sea dinámica excepción de especificación o noexcept-especificación
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) -
Opcional override o final, sólo es aplicable a las funciones miembro no estáticas
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) -
Trailing tipo de retorno, sólo es aplicable si ret es auto. Es útil si el tipo depende de los nombres de argumento, como template <class T, class U> auto add(T t, U u) -> decltype(t + u); o es complicada, como en 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 -
Constructor lista de inicialización, sólo se utiliza en los constructores
Original:
Constructor lista de inicialización, 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 -
La función opcional de bloque try. Si está presente, catch debe ser proporcionada
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 -
Secuencia opcional de catch-bloques, sólo aplicable de try se utiliza .
Original:
Optional sequence of catch-bloques, 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 -
El cuerpo de la función, una instrucción compuesta (posiblemente vacío)
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 -
La lista de parámetros
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.


[editar] Ejemplo 1: funciones no miembro

#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;
}

Output:

Hello, world
Hello, test
Hello, again
stoi() failed!
0


[editar] Ejemplo 2: funciones miembro

#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=
}

Output:

ctor1 called, data = 1
ctor2 called, data = 2
ctor2 failed, string was 'not a number'
2
ctor1 called, data = 3