为什么';t类中方法的顺序在C++;? 我一直在C++中编程很长一段时间,直到今天我才想到这个问题。

为什么';t类中方法的顺序在C++;? 我一直在C++中编程很长一段时间,直到今天我才想到这个问题。,c++,compiler-construction,C++,Compiler Construction,考虑以下代码: 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

考虑以下代码:

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

我对错误发生原因的理解(参见上文的
bar2()
注释)正确/不正确吗?无论哪种方式,我都希望通过一个简单的概述来了解单次C++编译器是如何编译上面给出的代码的。任何不熟悉的符号将被视为未定义的新符号。这是函数定义或头文件背后的方案


编译器可以首先定义一个列表,所以BAR()方法应该被正确编译,因为定义以前提供../P>> P>大部分的C++文件是从上到下解析的,所以在使用之前必须声明实体。 在您的类中,

bar2
b
无效,因为它们都使用了尚未声明的
my\u int\u type

“自上而下”解析规则的一个例外是在其类的定义中定义的成员函数。当解析这样一个成员函数定义时,它会被解析,就像它出现在类的定义之后一样。这就是为什么在
bar
中使用
my\u int\u type
是有效的

实际上,这:

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

这与能见度有很大关系。我想你的困惑可能是因为你只通过了一次。将类解析视为分两个阶段完成

  • 解析类定义
  • 解析方法实现

  • 这样做的好处是,我们可以从类成员函数中看到整个类。

    我很确定我以前问过这个问题…:-)@Mehrdad:我搜索了它,但在我脑海中出现的关键词中找不到:)