有没有办法传递一个字符串文字作为参考在C + + [英] Is there a way to pass a string literal as reference in C++

查看:249
本文介绍了有没有办法传递一个字符串文字作为参考在C + +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,如果值不能为NULL,那么通过引用传递而不是传递指针是很常见的。

Within C++ it is common to pass by reference instead of pointer if a value can not be NULL.

假设我有一个具有以下签名的函数,它通常与字符串文字一起使用。

Suppose I have a function with the following signature, which is often used with a string literal.

void setText( const char* text );

我想知道如何改变函数,使其接受一个引用优点是不接受NULL)?

I was wondering how I could change the function in such a way that it accepts a reference (and has the advantage not to accept NULL)?


  • 如果我将其更改为(const char& text )那么它将是一个单个字符的引用。从哪个地址可以在功能里面采取...但感觉不好。

  • If I would change it to (const char& text) then it would be a ref to a single char. From which the address can ba taken inside the function... but feels not nice.

另一个选项是(const std :: string& text)总是调用构造函数并做一些动态内存分配。

Another option would be (const std::string& text) which has the disadvantage that it always calls a constructor and does some dynamic memory allocation.

任何其他常见方法,或只是坚持 std :: string& code>或 char *

Any other common ways, or just stick to the std::string& or the char* ?

推荐答案

我只保留 const char * text 函数并添加一个重载 const std :: string&文本函数调用第一个 setText(text.c_str())

Honestly, I would just keep the const char* text function and add an overload const std::string& text function that calls the first one with setText(text.c_str())

这篇关于有没有办法传递一个字符串文字作为参考在C + +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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