我创建了一个这样的结构:
typedef struct Table {
#some members
} Table;
typedef struct Table *TableP; // pointer to Table
我想在以下功能中使用它(给我)
int insert(const TableP table, const void *key, DataP object)
但Clion突出了该功能中的表格,并发出警告:"' table'使用const限定的typedef类型声明;结果类型为' struct Table * const'而不是' const struct Table *'"
我不太清楚这意味着什么。我尝试将我的表结构更改为const,但它没有更改警告。
答案 0 :(得分:0)
struct Table * const
和const struct Table*
? struct Table * const
表示const pointer to struct Table
。
const struct Table*
表示pointer to a struct Table which is constant
。
在第一种情况下,指针是常量,但struct Table
不是。您可以修改表的属性。但是你不能将指针改为指向不同的表。
第二种情况,指针是非常量的。您可以指向任何结构表,但如果您尝试修改最初指向的表的属性,则会抛出错误。
您使用过typedef struct Table *TableP;
。现在const TableP
并不代表const struct Table*
。它只是意味着const pointer to a struct TableP
或struct TableP* const
。这就是编译器对你说的。
解决方案是在编写函数时直接在代码中使用struct Table *const table
。这就是你想要的 - 这意味着table is a constant pointer to a struct Table
。此外,它更具可读性和易用性。
这就是为什么将指针隐藏在typedef
后面并不是一个好主意 - 它会妨碍可读性并且会遇到像这样的一些奇怪的情况。
注意:最好的方法是简单地typedef
结构和指向它的指针应该直接使用。
typedef struct {
....
}Table;
void someFunc(Table *t);
答案 1 :(得分:0)
案例1 :
typedef struct Table *TableP;
此处Tablep
是指向结构表的指针。在你写作时
const TableP table
,它将被定义为 const struct Table *
所以const struct Table*
的意思是什么,意思是地址constant
,你不能改变地址,但你可以修改它的成员价值。
例如
struct Table {
int x ;
} v = {10}, v1 ={20};
typedef struct Table *Tablep;
int main() {
const Tablep table = &v ;//it becomes const pointer i.e you can't change address
table = &v1;// it's not possible.. address is contsant
// table->x = 99;// possible.. can change it's member value
return 0;
}
注意:const Tablep local
和Tablep const local
都相同。
我希望它有所帮助。