“ Typedef声明”之间的区别和“类声明” [英] Difference between "Typedef declaration" and "Class declaration"

查看:61
本文介绍了“ Typedef声明”之间的区别和“类声明”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The question is pretty straightforward. To further clarify, what exactly is the difference between Foo1 and Foo2 in the code below in terms of the way they are declared (e.g. one using class Foo1 { ... }; and the other using 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

The difference is subtle. In the first case you are creating a class with name Foo1, while in the second case you are creating an annonymous class and using a typedef to provide an aliased name Foo2.

第三个选项是:

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

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

That would create a class named Foo3 and create an alias Foo3 to refer to it.

微妙之处在于标识符的方式用该语言处理。当代码中存在标识符时,编译器将执行查找以知道的含义。查找将检查每个范围,首先在定义了大多数符号(用户定义类型除外)的全局标识符空间中进行检查,如果无法在此处找到标识符,则将在中进行查找用户定义的标识符空间。用户定义的类型属于第二个标识符空间,而 typedef -ed名称出现在第一组中。只有在两次查找均失败的情况下,编译器才会继续进行下一个封闭范围。

The subtleties are in how identifiers are handled in the language. When an identifier is present in the code the compiler will perform lookup to know what it means. The lookup will check in each scope, first in the global identifier space where most symbols (excluding user defined types) are defined, if it fails to locate the identifier there it will then look in the user-defined identifier space. User defined types belong to the second identifier space, while typedef-ed names are present in the first group. Only if both lookups fail, the compiler will move on to the next enclosing scope.

提供一个简单的测试案例,其中的区别非常明显:

To provide a simple test case where the differences are notable:

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
   }
}

这篇关于“ Typedef声明”之间的区别和“类声明”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆