c++ - c++ 和 c 中的命名空间

标签 c++ c syntax

并不是说在我的专业工作中我永远会编写如下代码,以下代码是合法的并且在 c++ 和 c 中编译时没有警告:

#include <stdlib.h>

typedef struct foo { int foo; } foo;

foo * alloc_foo () {
   return (struct foo*) malloc(sizeof(foo));
}   

struct foo * alloc_struct_foo () {
   return (foo*) malloc(sizeof(struct foo));
}   


foo * make_foo1 (int val) {
   foo * foo = alloc_struct_foo (); 
   foo->foo = 0;
   return foo;
}

struct foo * make_foo2 (int val) {
   struct foo * foo = alloc_foo();
   foo->foo = 0;
   return foo;
}

C 标准的第 6.2.3 节是 C 语言中合法且明确的原因:

6.2.3 Name spaces of identifiers
If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. Thus, there are separate name spaces for various categories of identifiers (label names; tags of structures, unions, and enumerations; members of structures or unions; and ordinary identifiers).

请注意,由于标签名称存在于它们自己的 namespace 中,我可以通过在某处使用标签 foo 使代码更加混淆。

添加以下内容,代码不编译:

int foo (foo * ptr) {
   return ++ptr->foo;
}   

所以,有两个问题,一个与 C 和 C++ 有关,另一个与 C++ 有关。

  • C/C++ 问题:为什么我不能定义函数 foo
    看来我应该能够定义函数 foo;函数名和变量名是“普通标识符”。但是如果我添加最后一点代码,我会得到error: redefinition of 'foo' as different kind of symbol
    问题:foo * foo; 是完全合法的,那么为什么 int foo (foo*); 不合法?

  • C++ 问题:这在 C++ 中是如何工作的?
    “ namespace ”的含义在 C++ 中与在 C 中具有截然不同的含义。我在 C++ 标准中找不到任何关于 C namespace 概念的内容,这就是使上述内容在 C 中合法的原因。
    问题:是什么让这在 C++ 中合法(章节和诗句首选)?

最佳答案

foo * foo; is perfectly legal, so why isn't int foo (foo*); legal?

因为在与您的函数相同的声明上下文中已经有一个名为 foo 的类型。在同一范围内不能有同名的类型和函数。

How does this work at all in C++?

因为您可以在嵌套范围内隐藏名称。当您声明 foo * foo 时,第一个 foo 指的是类型。第二个 foo 声明了一个变量——此时,类型 foo 是隐藏的。尝试在 foo * foo 之后声明 foo * baz,它应该会失败。

struct foo {};

void test() {
   foo * foo; // first `foo` is the type, second `foo` is the variable
   foo * baz; // first `foo` is the variable
}

关于c++ - c++ 和 c 中的命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7597634/

相关文章:

c++ - std::getline 与 std::fstream

c++ - 调试断言在删除分配的内存时失败

c - 无法从结构中的二维数组打印字符串?

python - 我以前从未见过的语法错误

syntax - 为什么在 Lisp 中某些情况下需要放置 #'?

c - 忽略分号 C 语法

c++ - 如何将多个字符连接成一个整数?

c++ - C++ 是否为纯虚拟类创建默认值 "Constructor/Destructor/Copy Constructor/Copy assignment operator"?

c - 多次调用malloc会不会浪费内存?

c - 使用指针设置操作