出现错误的 C++ 代码如下。我的 g++ 版本是 clang 版本 12.0.0 (clang-1200.0.32.27)
(代码是别人多年前写的,可能因为g++的版本更新,我现在不能成功运行了。)
typedef struct Cond{
int offset1;
bool (*comparator) (void * , void *, AttrType, int);
bool isValue;
void* data;
int offset2;
int length;
int length2;
AttrType type;
} Cond;
Cond *condList;
// Malloc the list of conditions to be met
condList = (Cond *)malloc(numConds * sizeof(Cond));
for(int i= 0; i < numConds; i++){
condList[i] = {0, NULL, true, NULL, 0, 0, INT};
}
编译器在 condList[i] = {0, NULL, true, NULL, 0, 0, INT}
行返回错误,
ql_nodejoin.cc:78:19: error: expected expression
condList[i] = {0, NULL, true, NULL, 0, 0, INT};
^
我该如何解决这个问题?
答案 0 :(得分:2)
快速修复是添加 -std=c++17
以支持此 C++ 功能。
实际的解决方法是更有效地使用 C++,例如使用 std::vector
并根据需要使用 emplace_back
创建条目:
// Malloc the list of conditions to be met
std::vector<Cond> condList;
for (int i= 0; i < numConds; ++i) {
condList.emplace_back(
0, // int offset1
nullptr, // bool (*comparator) (void * , void *, AttrType, int);
true, // bool isValue;
nullptr, // void* data;
0, // int offset2;
0, // int length;
0, // int length2;
INT // AttrType type;
);
}
它的行为很像一个常规数组,你仍然可以condList[i]
等等。
使用默认构造函数会容易得多:
struct Cond {
Cond() : offset1(0), comparator(nullptr), offset2(0), length(0), length2(0), type(INT) { };
// ... (properties) ...
}
现在你可以只用 emplace_back()
设置默认值,或者更简单,只需预先调整向量的大小:
std::vector<Cond> condList(numConds);
<块引用>
注意:typedef
在 C++ 中不是必需的,因为它在 C 中是必需的,因为 struct
不是必需的。
答案 1 :(得分:1)
我通过更改行解决了这个错误
condList[i] = {0, NULL, true, NULL, 0, 0, INT};
到
Cond c = {0, NULL, true, NULL, 0, 0, INT};
condList[i] = c;
一个小小的改变。我认为类型声明是必需的。