En el ciclo for a continuación:
struct Block
{
Block(int d) : data(d), next(nullptr) {}
int data;
Block* next;
};
Block* aList = new Block(1);
Block* bList = new Block(2);
for (Block* a = aList, *b = bList; a != nullptr; a = a->next, b = b->next)
if (aList->data != bList->data)
cout << "Difference found.\n";
No me gusta poner el * antes de b, pero, por supuesto, es necesario distinguir Bloque de Bloque *. Hay otra manera de hacer esto? for ((Block*) a, b...
no es una opción.
6 respuestas
Si no desea repetir *
, puede usar using
y crear un alias BlockPtr
que use en lugar de Block*
:
int main() {
using BlockPtr = Block*;
BlockPtr aList = new Block(1);
BlockPtr bList = new Block(2);
for (BlockPtr a = aList, b = bList; a != nullptr; a = a->next, b = b->next)
if (aList->data != bList->data)
cout << "Difference found.\n";
}
O retransmitir en auto
:
int main() {
auto aList = new Block(1);
auto bList = new Block(2);
for (auto a = aList, b = bList; a != nullptr; a = a->next, b = b->next)
if (aList->data != bList->data)
cout << "Difference found.\n";
}
Al declarar punteros, el *
pertenece al nombre, no al tipo. Eso significa que puede convertir b
en un puntero como
for (Block *a = aList, *b = bList; a != nullptr; a = a->next, b = b->next)
Estás intentando declarar dos punteros en una expresión.
Block* a = aList, b = bList;
Resulta que es parte de un bucle for
, pero igual
int * a, * b;
Son dos int
punteros, puedes usar
Block* a = aList, * b = bList;
En tu for
bucle.
Sí, solo usa:
Block* a = aList, *b = bList
Editar:
Opción 1: uso de Boost
#include <boost/typeof/typeof.hpp>
/*
...
*/
for (BOOST_TYPEOF_KEYWORD(Block*) a = aList, b = bList;...)
Otra opción es crear una sola variable del tipo que desee y usar su tipo para inicializar otras variables (similar a auto):
Opcion 2
Block* aList = new Block(1);
Block* bList = new Block(2);
for (decltype(aList) a = aList, b = bList; ...) ...
Opción 3: uso de Boost
#include <boost/typeof/typeof.hpp>
/*
Like the first option
*/
for (BOOST_TYPEOF(aList) a = aList, b = bList;...) ...
// ...
¿Qué pasa con la definición de un alias de tipo?
using BlockPtr = Block*;
for (BlockPtr a = aList, b = bList; a != nullptr; a = a->next, b = b->next)
if (aList->data != bList->data)
cout << "Difference found.\n";
Puede hacerlo así:
for (auto a = aList, b = bList; a != nullptr; a = a->next, b = b->next)
if (aList->data != bList->data)
cout << "Difference found.\n";
Nuevas preguntas
c++
C ++ es un lenguaje de programación de propósito general. Originalmente fue diseñado como una extensión de C, y tiene una sintaxis similar, pero ahora es un lenguaje completamente diferente. Use esta etiqueta para preguntas sobre el código (que se compilará) con un compilador de C ++. Utilice una etiqueta específica de la versión para preguntas relacionadas con una revisión estándar específica [C ++ 11], [C ++ 14], [C ++ 17] o [C ++ 20] etc.