簡體   English   中英

如何解決錯誤“預期表達式”?

[英]How can I solve the error 'expected expression'?

出現錯誤的 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};
                  ^

我該如何解決這個問題?

快速修復是添加-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);

注意:在 C++ 中不需要typedef ,因為它在 C 中是必需的,因為不需要struct

我通過更改行解決了這個錯誤

condList[i] = {0, NULL, true, NULL, 0, 0, INT};

Cond c = {0, NULL, true, NULL, 0, 0, INT};
condList[i] = c;

一個小小的改變。 我認為類型聲明是必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM