Nota parámetro de plantilla plantilla 4 Non-tipo

#include <string>
#include <iostream>
#include <stdexcept>

plantilla <nombre de tipo T, int MAXSIZE>
// plantilla <nombre de tipo T = int, int MAXSIZE = 100> //可以指定默认值!!!
clase de pila {
privadas:
elems T [MAXSIZE];
numElems int;
pública:
Pila ();
void push (T const y);
pop vacío ();
T superior () const;
bool vaciar () const {
numElems de retorno == 0;
}
Bool const completa () {
numElems retorno == MAXSIZE;
}
};

plantilla <nombre de tipo T, int MAXSIZE>
Pila <T, MAXSIZE> :: Pila (): numElems (0) {}

plantilla <nombre de tipo T, int MAXSIZE>
vacío Pila <T, MAXSIZE> :: empuje (T const y elem)
{
si (== numElems MAXSIZE)
{
tiro std :: out_of_range ( "Pila <> :: push (): pila es lleno");
}
Elems [numElems] = elem;
++ numElems;
}

plantilla <nombre de tipo T, MAXSIZE int>
vacío Pila <T, MAXSIZE> :: pop ()
{
si (numElems <= 0)
{
tiro std :: out_of_range ( "Pila <> :: pop (): pila vacía");
}

--numElems;
}


plantilla <nombre de tipo T, int MAXSIZE>
T Pila :: arriba () const <, MAXSIZE T>
{
si (numElems <= 0)
{
tiro std :: out_of_range ( "Pila <> :: arriba (): pila vacía") ;
}
Elems de retorno [numElems-1];
}

int main ()
{
try {
Pila <int, 20> int20Stack;
Pila <int, 40> int40Stack;
Pila <std :: string, 40> StringStack;
int20Stack.push (7);
std :: cout << int20Stack.top () << std :: endl;
int20Stack.pop ();
stringStack.push ( "Hola");
std :: cout << stringStack.top () << std :: endl;
stringStack.pop ();
stringStack.pop ();
}
Catch (const std :: excepción y ex) {
std :: cerr << "Excepción:" << ex.what () << std :: endl;
volver EXIT_FAILURE;
}
}

 

tipos de parámetros de plantilla no limitativos: número entero todos los días (incluyendo valores de enumeración) y el enlace de puntero externo al objeto.

No se permite a flotar, y la clase de objeto en el interior del objeto vinculado.

Ejemplo negativo:

plantilla <const char * name>

Myclass clase {

  ...;

};

const char * s = 'hola "; // errores globales puntero no se pueden utilizar como un parámetro de plantilla

Myclass <s> x; // error, S es un puntero de objeto enlace apuntando a una interna

Supongo que te gusta

Origin www.cnblogs.com/xpylovely/p/12482571.html
Recomendado
Clasificación