簡體   English   中英

如何在頭文件中聲明常量對

[英]How do I declare a constant pair inside my header file

#include <utility>
class C {
   private:
     const std::pair<int,int> corner1(1,1);
};

GCC報告錯誤:數字常量之前的預期標識符。

由於它是const,因此我需要在聲明時構造該對象,但我似乎無法獲得正確的語法。

由於它是const,因此我需要在聲明時構造該對象,但我似乎無法獲得正確的語法。

不,您只能在構造函數初始值設定項列表中初始化非整數類型-常量或不常量(至少在C ++ 11之前):

class C {
   private:
     const std::pair<int,int> corner1;
     C() : corner1(1,1) {}
};

但是在我看來,您不需要在每個實例中都復制該成員,因此我只是將其設置為靜態:

class C {
   private:
     static const std::pair<int,int> corner1;
};

//implementation file:
const std::pair<int,int> C::corner1(1,1);

如果您通過-std=c++11並且使用的是gcc的最新版本,則可以執行以下操作:

class C {
   private:
     const std::pair<int,int> corner1{1,1}; // Note curly braces
};

暫無
暫無

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

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