以以下示例为例,我想获得const
狗猫和对象:
// place 1 (type declaration)
const typedef struct Animal {
int id;
char* name;
} Animal;
// place 2 (singleton creation/assignment)
const Animal Dog = {1, "Dog"};
const Animal Cat = {2, "Cat"};
// place 3 (reference of singleton)
void main(void) {
const Animal dog = Dog;
const Animal* dogPtr = &Dog;
}
每次在这里我都使用const
前缀。上面三个地方都需要const
前缀吗,还是只在第一个地方需要,或者通过整个链的正确方法是什么,为什么?
const在第2位不需要。如果您删除了const,您仍然不能在声明之后更改Dog
和Cat
的值,因为您的const类型定义。同样,第3位也不需要const。
如果删除const类型定义,则需要const在第2位和第3位,这取决于您的目的。