通过参考返回静态字符数组 [英] return static character array by using reference

查看:167
本文介绍了通过参考返回静态字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我想写以下code的新版本:

Now I want to write a new version of the following code:

const char * f() {
     return "Hello";
} 
const char *pf = f();

我不知道如何使用参考而不是指针

我有一个想法,通过使用字符串

I have one idea by using string.

有没有办法解决这个问题的更直接的方式?

Is there a more straight way to solve this?

更新:

我读了答案和意见认真。我的另一种思路 是治疗的返回值作为为const char数组。但这种解决方案似乎过于复杂和不那么作为指针清晰。

I read the answer and comments carefully. I got another idea is to treat the return value as a const char array. But this solution seems too complicated and not so clear as a pointer.

推荐答案

如果你想知道的语法则定义会看看下面的方式

If you want to know the syntax then the definition will look the following way

#include <iostream>

const char ( & ( f() ) )[6] { return ( "Hello" ); }

int main()
{
    std::cout << f() << std::endl;
}

或者像@ Jarod42通知:您可以使用一个typedef的fiunction定义woild看起来简单

Or as @Jarod42 advices you can use a typedef that the fiunction definition woild look simpler

#include <iostream>

const char ( & ( f() ) )[6] { return ( "Hello" ); }

typedef const char ( &Array_Ref )[6];
Array_Ref g() { return ( "Hello" ); }

int main()
{
    std::cout << f() << std::endl;
    std::cout << g() << std::endl;

    Array_Ref s = g();
    std::cout << s << std::endl;    
}

如果你想使用std :: string的话会更好写功能

If you want to use std::string then it would be better to write the function as

std::string f() { return ( "Hello" ); }

这篇关于通过参考返回静态字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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