在下面的for循环中:
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";
我不喜欢将*放在b之前,但是当然需要将Block与Block *区分开。还有另一种方法吗? for ((Block*) a, b...
不适合。
答案 0 :(得分:5)
您可以这样做:
for (auto a = aList, b = bList; a != nullptr; a = a->next, b = b->next)
if (aList->data != bList->data)
cout << "Difference found.\n";
答案 1 :(得分:2)
如果您不想重复*
,则可以使用using
并创建一个别名BlockPtr
,而不是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";
}
或在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";
}
答案 2 :(得分:1)
是的,只需使用:
Block* a = aList, *b = bList
编辑:
#include <boost/typeof/typeof.hpp>
/*
...
*/
for (BOOST_TYPEOF_KEYWORD(Block*) a = aList, b = bList;...)
另一个选择是创建所需类型的单个变量,并使用该类型来初始化其他变量(类似于auto):
Block* aList = new Block(1);
Block* bList = new Block(2);
for (decltype(aList) a = aList, b = bList; ...) ...
#include <boost/typeof/typeof.hpp>
/*
Like the first option
*/
for (BOOST_TYPEOF(aList) a = aList, b = bList;...) ...
// ...
答案 3 :(得分:1)
声明指针时,*
属于名称,而不是类型。这意味着您可以使b
这样的指针
for (Block *a = aList, *b = bList; a != nullptr; a = a->next, b = b->next)
答案 4 :(得分:1)
您试图在一个表达式中声明两个指针。
Block* a = aList, b = bList;
它恰好是for
循环的一部分,但是就像
int * a, * b;
是两个int
指针,可以使用
Block* a = aList, * b = bList;
在您的for
循环中。
答案 5 :(得分:0)
仅定义type alias怎么样?
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";