【问题标题】:What is the type of "abc" in C++? [duplicate]C++中“abc”的类型是什么? [复制]
【发布时间】:2015-01-21 20:36:05
【问题描述】:

C++ 中“abc”的类型是什么?候选人可以是 const char*char*

还有什么可以想到的吗?

【问题讨论】:

  • 其实是const char[4]
  • 我在使用 c++11 std::regex_replace 时遇到了一个奇怪的 clang++ 编译器行为。编译器不接受:std::string text = "Quick brown fox";std::regex vowel_re("a|e|i|o|u"); 错误 --> std::cout << '\n' << std::regex_replace(text, vowel_re, "[$&]") << '\n'; 有效 --> std::cout << '\n' << std::regex_replace(text, vowel_re, std::string("[$&]")) << '\n';
  • @tisch 这是一个完全无关的问题(我相信你必须通过std::string{"[$&]"}
  • @Barry 非编译行来自:en.cppreference.com/w/cpp/regex/regex_replace 这就是我想知道的原因。
  • @tisch:然后问这个问题。请注意,示例中的代码运行良好,至少使用 g++ (GCC) 4.9.2。

标签: c++


【解决方案1】:

在我尝试过的教程点上:

#include <iostream>
#include <typeinfo>
using namespace std;

int main()
{
   cout << typeid("abc").name() << endl; 
   cout << typeid ( const char * ).name() << endl;
   cout << typeid( char * ).name() << endl;
   cout << typeid( char[4]).name() << endl;
   cout << typeid( const char[4]).name() << endl;

   return 0;
}

输出是:

A4_c
PKc
电脑
A4_c
A4_c

似乎是 char[4] 或 const char[4] 但肯定不是 char* 或 const char*

【讨论】:

  • 它是 const char[4],根据 C++11 §2.14.5 ¶8 (普通字符串文字和 UTF-8 字符串文字也称为窄字符串文字。窄字符串字面量的类型为“array of n const char”,其中 n 是字符串的大小,定义如下,并且具有静态存储持续时间 (3.7)。)
  • 不要使用typeid 来区分类型。标准有时会保证给你错误的答案。
  • 我猜它也会是 const char[4]。我用typeid来说明。要获得更纯粹的答案,您可能会为 char[N] 中的数字编写可能模板化的重载,然后查看打印的是哪个。
  • C 中的 char[] 和 char[4] 有什么区别? C中的数组类型包括长度吗?
猜你喜欢
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2019-08-10
  • 2015-09-05
  • 2013-05-01
相关资源
最近更新 更多