Nonstatic member as a default argument of a nonstatic member function

后端 未结 9 1019
攒了一身酷
攒了一身酷 2020-11-28 05:56
struct X
{
   X():mem(42){}
   void f(int param = mem) //ERROR
   {
      //do something
   }
private: 
   int mem;
};

Can anyone give me just one

9条回答
  •  有刺的猬
    2020-11-28 06:20

    Default arguments are evaluated in two distinct steps, in different contexts.
    First, the name lookup for the default argument is performed in the context of the declaration.
    Secondly, the evaluation of the default argument is performed in the context of the actual function call.

    To keep the implementation from becoming overly complicated, some restrictions are applied to the expressions that can be used as default arguments.

    • Variables with non-static lifetime can't be used, because they might not exist at the time of the call.
    • Non-static member variables can't be used, because they need an (implicit) this-> qualification, which can typically not be evaluated at the call site.

提交回复
热议问题