gpt4 book ai didi

c++ - "Typedef declaration"和 "Class declaration"之间的区别

转载 作者:行者123 更新时间:2023-11-30 01:28:09 27 4
gpt4 key购买 nike

这个问题很简单。为了进一步阐明,下面代码中的 Foo1Foo2 在它们的声明方式方面到底有什么区别(例如,使用 class Foo1 { 。 .. }; 而另一个使用 typedef class { ... } Foo2;)?

class Foo1 {
public:
void bar() { }
};

typedef class {
public:
void bar() { }
} Foo2;

int main()
{
Foo1 f1;
f1.bar();
Foo2 f2;
f2.bar();
return 0;
}

最佳答案

区别很微妙。在第一种情况下,您正在创建一个名为 Foo1 的类,而在第二种情况下,您正在创建一个匿名类并使用 typedef 提供别名 Foo2.

第三个选项是:

typedef class Foo3 {
public:
void bar() {}
} Foo3;

这将创建一个名为 Foo3 的类,创建一个别名 Foo3 来引用它。

微妙之处在于标识符在语言中的处理方式。当代码中出现标识符时,编译器将执行查找以知道它的含义。查找将检查每个范围,首先是在定义了大多数符号(不包括用户定义类型)的全局标识符空间中,如果它无法在那里找到标识符,它将在中查找用户定义的标识符空间。用户定义的类型属于第二个标识符空间,而 typedef 编辑的名称存在于第一组中。只有当两次查找都失败时,编译器才会移动到下一个封闭范围。

提供一个差异显着的简单测试用例:

class A {};
typedef class {} B;
typedef class C {} C;
void A(); // correct: no collision
//void B(); // error, identifier B already used with a different meaning!
//void C(); // "
namespace test {
void B();
void C();
void f() {
class A a; // creates variable of type ::A
A(); // calls function ::A
B(); // calls function test::B()
//class B b; // error: B does not denote a user-defined type name
C(); // calls function test::C()
class C c; // creates variable of type ::C
}
}

关于c++ - "Typedef declaration"和 "Class declaration"之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7970116/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com