为什么在C ++中类中的方法的顺序不重要? [英] Why doesn't the order of methods in a class matter in C++?

查看:87
本文介绍了为什么在C ++中类中的方法的顺序不重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在C ++中编程了一段时间,我从来没有想过这个问题,直到今天。

I have been programming in C++ for quite some time and I never thought about this until today.

考虑下面的代码:

struct foo
{
  // compiles fine
  void bar()
  {
    a = 1;
    my_int_type b;
    b = 5;
  }

  // Just a declaration, this fails to compile, which leads me to assume that
  // even though the bar() method is declared and defined all at once, the
  // compiler looks/checks-syntax-of the class interface first, and then compiles
  // the respective definitions...?
  void bar2(my_int_type); // COMPILE ERROR

  my_int_type       b; // COMPILE ERROR because it comes before the typedef declaration
  typedef int       my_int_type;
  my_int_type       a;

  void bar3(my_int_type); // compiles fine
};

int main()
{
  foo a;
  a.bar();
  return 0;
}

是我理解错误发生的原因 $ c> bar2()上面的注释)正确/不正确?无论哪种方式,我将欣赏一个简单的概述如何单程C ++编译器将编译上述代码的答案。

Is my understanding of why the errors occur (see bar2() comment above) correct/incorrect? Either way, I would appreciate an answer with a simplistic overview of how a single-pass C++ compiler would compile the code given above.

推荐答案

p>在大多数情况下,C ++文件是从上到下解析的,所以实体必须在使用之前声明。

For the most part, a C++ file is parsed top-to-bottom, so entities must be declared before they are used.

在你的类中, bar2 b 无效,因为它们都使用 my_int_type 尚未声明。

In your class, bar2 and b are invalid because they both make use of my_int_type, which has not yet been declared.

从上到下解析规则的一个例外是在其类的定义内定义的成员函数。当这样的成员函数定义被解析时,它被解析,好像它出现在类的定义之后。这就是为什么您在 bar 中使用 my_int_type 有效的原因。

One exception to the "top-to-bottom" parsing rule is member functions that are defined inside the definition of their class. When such a member function definition is parsed, it is parsed as if it appeared after the definition of the class. This is why your usage of my_int_type in bar is valid.

有效地,这:

struct foo
{
    void bar()
    {
        my_int_type b;
    }

    typedef int my_int_type;
};

与以下相同:

struct foo
{
    void bar();

    typedef int my_int_type;
};

inline void foo::bar()
{
    my_int_type b;
}

这篇关于为什么在C ++中类中的方法的顺序不重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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