【问题标题】:Few doubts regarding 1.constructor and 2.array definition at compile time编译时关于 1.constructor 和 2.array 定义的几个疑问
【发布时间】:2011-08-12 19:36:50
【问题描述】:

请帮助我清除以下问题的概念: (在linux,gcc上执行和测试)

问题一:

在下面的简单示例中,A a() 到底是什么意思?

我发现这不是默认构造函数的定义,而是a()是一个返回类型为A的函数。

如果是正确的,那么为什么这段代码没有给我任何链接器错误或运行时错误。这段代码运行和链接顺畅,就好像它知道函数 a() 的定义一样。

class A
{
  public:
     void print()
     {
       printf("In class A\n");
     }
};


int
  main()
  {
    A a();
    //a.fun();  //throws error "request for member ‘fun’ in ‘a’, which is of type ‘A()’"
  } 

问题 2。

在以下代码中,数组 b 的定义会引发错误。 我无法找到这种行为的确切原因。

int a[]={3,4,21,5,7,86};
 int b[a[3]];     //this throws error why???

 int
  main() { ... }

【问题讨论】:

    标签: c++ arrays function constructor


    【解决方案1】:

    问题 1

    这被称为most vexing parse。以下:

    A a();
    

    是一个函数声明。您没有调用该函数,因此链接器没有义务解决它。这就解释了为什么您没有看到任何错误。

    问题 2

    数组的大小必须用一个常量表达式来指定。 a[3] 不是常量表达式。

    【讨论】:

    • 我希望他们选择了一个更好的名字,“最令人烦恼的解析”听起来很愚蠢。
    • @Seth:我认为这不是正式的术语。这只是人们给它起的昵称。
    • @Oli:我认为是 Scott Meyers 最先使用了这句话。
    • I found that this is not a definition of default constructor but a() is a function with return type is A. OP 似乎知道那是什么。他的问题是why this code does not give me any linker error or runtime error.
    • @Mooing:嗯,原因是因为函数声明是有效的 C++,我想!答案已更新,不过...
    【解决方案2】:

    A a(); 这告诉编译器一个函数 a 存在。编译器说OK!但由于它从未使用过,链接器从不检查它,因此没有链接器错误。

    int a[]={3,4,21,5,7,86}; 不幸的是,数组的元素不被视为compile time constants,因此不能用于初始化数组或模板参数。您必须以另一种方式设置 B 的大小,或者在运行时动态设置:int *b = new int[a[3]];

    【讨论】:

      【解决方案3】:

      关于问题2:c++不支持可变数组大小

      【讨论】:

        【解决方案4】:
        A a();
        

        它是一个名为 a 的函数声明,它不接受任何参数并返回 A。它不是变量声明。


        int a[]={3,4,21,5,7,86};
        int b[a[3]];     //this throws error why???
        

        在 C++ 中,数组的大小应该是 const 表达式,但 a[3] 不是 const 表达式。因此错误。

        但是如果你这样做:

        const int a=21;
        int b[a];   //okay - now a is const expression.
        

        那就没事了。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-08-17
          • 2010-10-07
          • 2018-08-05
          • 2015-09-16
          • 2011-07-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多