[英]struct keyword in function parameter, and const-correctness
我的庫中有一個不透明類型,定義為:
typedef struct MyOpaqueType* MyType; // easier to type for client code
我不能使用 typedef 傳遞指向 const 結構的指針,所以一些函數看起來像:
void UsePointerToConst ( const struct MyOpaqueType * )
代替:
void UserPointerToConst( const MyType ) // can't use, is really constant pointer
所以,鑒於此,我有兩個問題:參數列表中的 struct 關鍵字是否僅在 C 中需要? 有一個更好的方法嗎? 我應該創建一個typedef,例如:
typedef const struct MyOpaqueType* ConstantMyType; ?
參數列表中的struct關鍵字是不是只有C才需要?
是的。 請參閱 Jens Gustedt 的回答。
有一個更好的方法嗎?
只需typedef
結構,而不是指針。 這更好,因為
typedef
而不是 { MyOpaqueType
、 MyOpaqueType *
、 MyOpaqueType const *
、 MyOpaqueType *const
和MyOpaqueType const *const
} 以及所有涉及restrict
的變體(在 C++ 中不存在),FILE *
)。 也沒有危險; 當有人忘記*
時,他們會收到編譯器錯誤。
在 C++ 中,只要沒有具有該名稱的其他標識符,就會假定與struct
同名的typedef
。 所以類似於 function stat
接收struct stat*
作為參數:
int stat(const char *path, struct stat *buf);
C++ 甚至允許。 (這是一個真實的例子。)
所以你總是更好地使用前向聲明,比如
typedef struct toto toto;
它將toto
令牌保留在標識符和結構名稱空間中。 然后您可以為 C 和 C++ 聲明您的 function 接口。 但是,如果您也想從 C 訪問它,請不要忘記extern "C"
。
另請參閱: 關於 SO 和結構標簽的這個答案不是 C++ 中的標識符。
C++ 中根本不需要 typedef。 只需使用前向聲明:
struct MyType;
然后在需要時傳遞MyType const *
、 MyType *
、 MyType const &
等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.