为什么这不能作为成员函数中的默认参数传递? [英] Why this can not be passed as default parameter in member function?

查看:218
本文介绍了为什么这不能作为成员函数中的默认参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图传递当前的length值作为默认参数作为一个函数参数。
,但编译器显示错误,


'this'不能在此上下文中使用


可以告诉我我犯的错误是什么。 ?

  class A 
{

private:
int length;
public:
A();
void display(int l = this-> length)
{
cout<<length is<<<< endl;
}

};


int main()
{

A a;
a.display();
return 0;

}


解决方案

函数:

  void display(int l = this-> length)
/ pre>

在概念上等价于:

  A * this,int l = this-> length); //由编译器翻译

这意味着你在表达式中使用一个参数默认参数为C ++中不允许的其他参数,如§8.3.6/ 9(C ++ 03)所述,


每次调用函数时都会计算参数。 函数参数的计算
的顺序是
unspecified
因此,函数的参数
不应在
默认参数表达式
中使用,即使
未评估。


请注意,C ++不允许这样:

  int f int a,int b = a); // illegal:§8.3.6/ 9 






解决方案是添加一个没有参数的重载:

  void display()
{
显示(长度); //调用另一个!
}

如果您不想再添加一个函数,一个不可能的默认值。例如,由于它描述了永远不会为负的长度,因此您可以选择 -1 作为默认值,并且可以实现您的函数as:

  void display(int l = -1)
{
if(l < -1)
l = length; //使用它作为默认值!
//开始使用l
}


I was trying to pass the current value of length as the default parameter as a function argument . but compiler is showing error that

" 'this' may not be used in this context"

can any one tell me what is the mistake I have committed. ?

class A
{

    private:
    int length;
    public:
    A();
    void display(int l=this->length)
    {
        cout<<"the length is "<<l<<endl;
    }

};


int main()
{

    A a;
    a.display();    
    return 0;

}

解决方案

Your member function:

void display(int l=this->length)

is conceptually equivalent to this:

void display(A * this, int l=this->length); //translated by the compiler

which means, you're using one parameter in an expression which is the default argument for other parameter which is not allowed in C++, as §8.3.6/9 (C++03) says,

Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in default argument expressions, even if they are not evaluated.

Note that C++ doesn't allow this:

int f(int a, int b = a); //illegal : §8.3.6/9


The solution is to add one overload which takes no parameter as:

void display()
{
    display(length); //call the other one!
}

If you don't want to add one more function then choose an impossible default value for the parameter. For example, since it describes length which can never be negative, then you may choose -1 as the default value, and you may implement your function as:

void display(int l = -1)
{
      if ( l <= -1 ) 
           l = length; //use it as default value!
      //start using l 
}

这篇关于为什么这不能作为成员函数中的默认参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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