我正在尝试对 int 和 *node(节点是自定义结构)使用条件运算符 (?)。这是我的代码,以及由此产生的错误。
节点:
struct node {
int num;
node *next;
};
条件执行:
void PrintNodes(node *head_p) {
int done = 0;
while (!done) {
PrintNodeData(head_p);
// if (head_p->next==NULL) {
// done++;
// } else {
// head_p++;
// }
((head_p->next==NULL) ? done : head_p)++;
}
}
我在条件语句上方的注释中有等效的 if...then...else
语句,我只是希望能够将其缩减为一行。
编辑
错误:
test.cc: In function ‘void PrintNodes(node*)’:
test.cc:28:36: error: operands to ?: have different types ‘int’ and ‘node*’
make: *** [all] Error 1
最佳答案
只是不要。做明确的事情。
长答案是 C++ 有一个类型系统,而你试图做的事情违反了它。
关于具有不同类型作为参数的 C++ 条件运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16715152/