微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

有没有手动超载相应的成员函数调用一个重载与成员作为参数?

我正在尝试一些东西

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.

原文地址:https://www.jb51.cc/c/112869.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐