函数重载与c ++中的默认参数 [英] function overloading vs default argument in c++

查看:208
本文介绍了函数重载与c ++中的默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有一个混乱或说我更需要了解的东西。我有一个过程和另一个重载的过程相同。

Hi i have a confusion or to say more i need to understand something. I have a procedure and another overloaded procedure of same.

    string conct (string a, string b) {
      string str = conct(a, b, "string");
      return str;
    }

    string conct (string a, string b, const char* c) {
      // do the processing;
      return concatenated_string;
    }

是可能的,而不是有两个重载的函数,如果i make c 在重载函数中作为默认参数。所以即使有人只传递两个参数,我可以只有一个函数来处理这种情况。

is it possible that instead of having two overloaded functions, if i make c in the overloaded function as default argument. So that even if someone passes only two arguments, i can just have one function to handle that case.

但我的主要关注在第三个参数,目前 const char * c 。所以如果我使它像 const char * c =string,将是正确的方式来处理使用默认参数的一个函数删除重载的情况。

But my main concern comes in the third argument which is currently const char* c. So if i make it to something like const char* c = "string", would it be correct way to handle the case of removing overloading with one function with default argument.

我看到这篇文章这里,但这似乎集中在编译,而不是我有的混乱。

I saw the post here but that seems to be focused on compilation and not the confusion i have.

推荐答案

是的,您可以用一个函数和默认参数替换重载的函数:

Yes, you can replace your overloaded functions with one function and a default argument:

string conct (string a, string b, const char* c = "string") {
  // do the processing;
  return concatenated_string;
}




    当您重载函数时,
  • 如果一个重载只是作为一个薄的包装器在你的情况下,那么优化器可以消除额外的工作。

  • 默认参数设置在调用者的位置,而不是在函数内部,因此默认参数必须是公开可见的,更改它们需要重新编译所有调用者。有一个像你的重载psuedo-default参数成为隐藏的细节。

  • 这篇关于函数重载与c ++中的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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