使用类成员作为成员函数的默认参数 [英] Using a class member as a default argument for a member function

查看:175
本文介绍了使用类成员作为成员函数的默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了手动重载相应的成员函数并以成员作为参数调用第一次重载之外,还有其他方法吗?

Is there another way than manually overloading the corresponding member function and calling the first overload with the member as the argument?

我正在尝试以下方式: / p>

I am trying something along the lines of

class test
{
    string t1="test";

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

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

当前,我想这没有技术上的原因。

Currently I guess there is no technical reason why this should not work.


  • 是否有解决方案,除非手动重载和设置参数?

  • 为什么这不起作用,是否有技术原因?

推荐答案

[dcl.fct.default] / 8:

[dcl.fct.default]/8:


关键字 this 不能在成员函数的默认参数中使用。

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

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

This is a special case of a general problem: You cannot refer to other parameters in a default argument of a parameter. I.e.

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:

Which is basically what the compiler transforms a member function of the form void f(int i = j) {} into. This originates from the fact that the order of evaluation of function arguments and the postfix-expression (which constitutes the object argument) is unspecified. [dcl.fct.default]/9:


每次调用函数时都会评估默认参数。
函数参数的求值顺序未指定。因此,即使未对函数的参数进行求值,也不应在默认的
参数中使用该函数的参数。

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

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