下标字符串文字 [英] Subscripting a string literal

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

问题描述

用字母数字下标是一种常见/有效的技术吗?发生了哪些隐式转换? 示例

Is subscripting an alphanumeric a common/valid technique? And what are the implicit conversions that take place ? example :

#include <iostream>
using namespace std;

int main() 
{
    int k(2);
    cout << "Hello"[k] << endl;
    cout << (k-1)["Hello"] << endl;
    // your code goes here
    return 0;
}


推荐答案

当然没有什么好可以写作

Of course there is no greate sense to write

cout<< 你好 [0]<< endl;

cout << "Hello"[0] << endl;

而不是简单

cout<< ‘H’<< endl;

cout << 'H' << endl;

但是有时还是有

#define Hello "Hello"

在某些(尤其是C)程序中。

in some (especially C) programs.

在这种情况下,有一定的写意感

In this case there is some sense to write

cout<<你好[0]<< endl;

cout << Hello[0] << endl;

但是最好定义

const char *Hello = "Hello";

const char Hello[] = "Hello";

之间没有区别

"Hello"[0]

0["Hello"]

因为根据C ++标准


表达式E1 [E2](根据定义)与*((E1)+ (E2))

The expression E1[E2] is identical (by definition) to *((E1)+(E2))

但是第二条记录只会使代码的读者感到困惑。

However the second record only confuses readers of the code.

对于转换,然后将类型为 const char [6] 的字符串文字 Hello的左值转换为类型为 const char * 。然后使用指针算法计算表达式*((E1)+(E2))。

As for the conversion then lvalue of string literal "Hello" that has type const char[6] is converted to type const char *. and then expression *((E1)+(E2)) is calculated using the pointer arithmetic.

这篇关于下标字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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