【问题标题】:Difference between char in C and C++? [duplicate]C和C++中char的区别? [复制]
【发布时间】:2021-12-30 00:29:20
【问题描述】:

我知道 C 和 C++ 是不同的语言。

代码 - C

#include <stdio.h>

int main()
{
    printf("%zu",sizeof('a'));
    return 0;
}

输出

4

代码-C++

#include <iostream>
int main()
{
    std::cout<<sizeof('a');
    return 0;
}

输出

1

https://stackoverflow.com/a/14822074/11862989 在这个答案中用户 Kerrek SB(438k Rep.) 讲述了 C++ 中的类型,也没有提到 char 既没有 int 也没有提到。

C++中的char是整型还是严格的char类型?

【问题讨论】:

  • C 中的字符文字是 int,但在 C++ 中,它是 char。
  • 是的,char 在 C 和 C++ 中都是整数类型。不同之处在于字符文字(如'a')在C++ 中具有char 类型(因此大小为1)而在C 中具有类型int(大小实现已定义,通常不是1)。
  • 差异的一个很好的原因是:C++ 有重载的方法。例如:void method( char c ); 和 void method( int n );。如果字符常量是 C++ 中的 int 值,则调用 method( 'a' ); 将调用 int 方法。因为 C 没有函数重载,所以在 C 中不会发生这种情况。

标签: c++ c types char integral


【解决方案1】:

C++中的char是整型还是严格的char类型?

type_traits 的使用让您知道类型:

#include <iostream>
#include <type_traits>
int main()
{
    std::cout << std::is_integral<char>();
}

输出:

1

【讨论】:

    【解决方案2】:

    C++中的char是整型还是严格的char类型?

    字符类型,例如 char,在 C++ 中是整数类型。

    C中窄字符常量的类型为int,而C++中窄字符常量的类型为char。

    【讨论】:

    • 窄字是什么意思,能详细说明吗?
    • @AbhishekMane 'a' 是字符常量。它在 C 中具有 int 类型,在 C++ 中具有 char 类型
    • while the type of narrow character literal in C++ is char 是什么意思?
    • @eerorika 你能回答我上面的 2 个 cmets 吗?
    • @AbhishekMane 窄字符文字例如 'a'。这与L'a' 等宽字符文字形成对比。这种文字有不同的类型——宽字符类型。 C++ 中的所有表达式都有一个类型。 1 的类型是 int。 malloc(1) 的类型是 void*。 'a' 的类型是 char。
    【解决方案3】:

    正如其他人提到的,在 C 中,'a' 是 char 常量并被视为整数。 在 C++ 中,它是不可或缺的。

    您还可以使用 RTTI(运行时类型信息)检查 C++ 中 char c = 'a' 和 'a' 之间的区别,如下所示:

    #include <iostream>
    #include <typeinfo>
    using namespace std;
      
    int main()
    {
    
        char c = 'a';
      
        // Get the type info using typeid operator
        const type_info& ti2 = typeid('a');
        const type_info& ti3 = typeid(c);
      
    
        // Check if both types are same
        if (ti2 != ti3)
            cout << "different type" << endl;
        else
            cout << "same type"<< endl;
      
        return 0;
    }
    

    输出为:same type。

    但是,char c = 'a' 和 'a' 在 C 中并不相同。

    【讨论】:

      猜你喜欢
      • 2013-05-16
      • 2019-06-10
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      相关资源
      最近更新 更多