加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用类成员作为成员函数的默认参数

发布时间:2020-12-16 06:02:54 所属栏目:百科 来源:网络整理
导读:有没有手动超载相应的成员函数和调用第一个重载与成员作为参数? 我正在尝试一些东西 class test{ string t1="test"; testfun( string val = this-t1 ) { /* modify val somehow */ }}; (测试:http://goo.gl/36p4CF) 目前我猜想没有技术原因,为什么这不行.
有没有手动超载相应的成员函数和调用第一个重载与成员作为参数?

我正在尝试一些东西

class test
{
    string t1="test";

    testfun( string& val = this->t1 )
    { /* modify val somehow */ }
};

(测试:http://goo.gl/36p4CF)

目前我猜想没有技术原因,为什么这不行.

>有没有解决方法这样做,除了手动重载和设置参数?
为什么这不工作,有技术原因吗?

解决方法

[dcl.fct.default] / 8:

The keyword this shall not be used in a default argument of a member function.

这是一个一般问题的特殊情况:您不能在参数的默认参数中引用其他参数.即

void f(int a,int b = a) {}

形形色色那么会是

class A
{
    int j;
};

void f(A* this,int i = this->j) {}

这基本上是编译器将成员函数形式为void f(int i = j){}转换成的.这源自于功能参数的评估顺序和后缀表达式(构成对象参数)的顺序是未指定的. [dcl.fct.default] / 9:

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 a default argument,even if they are not evaluated.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读