繁体   English   中英

将空字符串作为参数传递给函数

[英]Passing null string to function as an argument

在不创建变量的情况下将 NULL 字符串传递给函数的正确方法是什么? 我看到以下代码出现编译错误,我不想更改定义。 也可能必须对字符串进行更改,因此不想将其标记为常量类型。

#include <iostream>
#include <string>

using namespace std;
void
myfunc(int i,  string &my) {
   if (my.empty()) {
      cout << "Empty" << endl;
   } else {
      cout << "String is " << my <<endl;
   }
}
int main ()
{
  std::string str1 ("Test string");
  myfunc(1, str1);
  std::string str2 ("");
  myfunc(2, "");
  return 0;
}`

my1.cpp:18:错误:从“const char *”类型的临时变量中对“std::string&”类型的非常量引用无效初始化 my1.cpp:6:错误:在传递“void myfunc”的参数 2( int, std::string&) '

以下编译但我不想创建局部变量

#include <iostream>
#include <string>

using namespace std;
void
myfunc(int i,  string &my) {
   if (my.empty()) {
      cout << "Empty" << endl;
   } else {
      cout << "String is " << my <<endl;
   }
}
int main ()
{
  std::string str1 ("Test string");
  myfunc(1, str1);
  std::string str2 ("");
  myfunc(2, str2);
  return 0;
} 

此处的解决方案是使重载没有字符串参数。

void myfunc(int i,  string &my) {
      cout << "String is " << my <<endl;
}

void myfunc(int i) {
   cout << "Empty" << endl;
}

int main ()
{
  std::string str1 ("Test string");
  myfunc(1, str1);
  myfunc(2);
}

这是最简单,最清晰的解决方案,可以准确传达您的意图和功能。

您不应该尝试按照自己的方式进行操作,因为如果要修改参数,则参数应为“非常量引用”,因此它不能绑定到临时变量。 因此,您不能将字符串文字传递给它。


如果您想明确表示您不传递字符串,则可以创建一个标签ala nullptr ,尽管当上述变体清晰易懂且每个人都乍看之下时,我不建议这样做。

struct no_string_tag_t {};
constexpr no_string_tag_t no_string_tag;

void myfunc(int i,  string &my) {
      cout << "String is " << my <<endl;
}

void myfunc(int i, no_string_tag_t) {
   cout << "Empty" << endl;
}

int main ()
{
  std::string str1 ("Test string");
  myfunc(1, str1);
  myfunc(2, no_string_tag);
}

如果您确实需要单个功能,则语义正确的版本将具有可选的引用。

auto foo(int i, std::optional<std::reference_wrapper<std::string>> my)
{
    if (my)
        cout << "String is " << my <<endl;
    else
        cout << "no string" << endl;

}
int main ()
{
  std::string str1 ("Test string");
  myfunc(1, str1);
  myfunc(2, std::nullopt);
}

如果您想保留功能签名并且仍然能够暂时传递它,那么您就不走运了。 C++具有安全功能,因为它不允许非常量首选项绑定到临时文件。 这种限制的原因是,通过临时引用尝试修改临时文件很可能是错误,而不是程序员的意图,因为临时文件无论如何都会消失。

您不能将临时变量传递给非常量引用参数。 函数返回后,作为临时对象的对象将被销毁。 函数对对象所做的任何更改都将丢失。

如果您希望有机会修改字符串,则可以通过const引用获取字符串并返回修改后的字符串。

string myfunc( int i, string const &s );
:
str1 = myfunc( 1, str1 );
auto result2 = myfunc( 2, "" );

您的另一个选择是使用指向可以为空的字符串的指针。

void myfunc( int i, string *s ) {
    if (!s) {
        cout << "Empty" << endl;
    } else {
        cout << "String is " << *s <<endl;
    }
}

myfunc( 1, &str1 );
myfunc( 2, nullptr );

您可以在函数调用中省略 1 个或多个参数,只要这些参数是顺序中的最后一个参数或该函数中原型化的参数。

如果在调用函数时省略了参数,您也可以给出 padron 值。

using namespace std;

void sTest(int a, string x ="TEST", int z=0);

void sTest(int a, string x, int z)
 {
    cout << x;

 }

int main() 
{   
   sTest(5); // displayed “TEST”
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM