简体   繁体   English

为什么我们可以说 ' char *c = "Hello"; ' 在 C++ 中

[英]Why can we say ' char *c = "Hello"; ' in C++

When I do-当我做-

#include <iostream>

int main(){
    char *p = "Hello";
}

it works fine, but doing它工作正常,但做

#include <iostream>

int main(){
    char *p = 'H';
    // OR
    int *x = 5;

}

gives an error: invalid conversion from 'char' to 'char*' [-fpermissive] / 'int' to 'int*'给出错误:从“char”到“char*”的无效转换[-fpermissive]/“int”到“int*”

The issue here is that C++ is a strongly typed language.这里的问题是 C++ 是一种强类型语言。 You have to make sure the type on the right of an = is the same as the type on the left (or there is some well defined conversion that allows the compiler to convert between types).您必须确保=右侧的类型与左侧的类型相同(或者有一些明确定义的转换,允许编译器在类型之间进行转换)。

So we need to know what types literals are: Using a double quote creates a string literal of type char const[] while using a single quote creates a character literal of type char const .所以我们需要知道什么类型的文字是:使用双引号创建一个char const[]类型的字符串文字,而使用单引号创建一个char const类型的字符文字。

You will have to bear with me on the const part.你将不得不忍受我的const部分。 That makes the discussion much more complicates so we will gloss over it initially.这使讨论变得更加复杂,因此我们将首先对其进行掩饰。

We also need to know that when arrays are used in expressions they very easily decay into pointers.我们还需要知道,在表达式中使用数组时,它们很容易退化为指针。 So it most situations the type of char const[] will decay into char const* .所以在大多数情况下, char const[]的类型会衰减为char const*

This should work:这应该有效:

char const* p = "Hello";    // This is valid.
                            // Both left and right sides have the same type.
                            // After you consider the array decay into a pointer.

On the other hand另一方面

char const* p = 'H';        // The type on the right is `char const'
                            // While the type on the right has a pointer in it.

Now there are some automatic conversions at play here.现在这里有一些自动转换。
In the original C++03 the compiler was allowed to auto convert string literals from char const* to char* .在最初的 C++03 中,编译器被允许将字符串文字从char const*自动转换为char* This is a relic from the old C language that was not as strict on type checking as C++ is now.这是旧 C 语言的遗物,它在类型检查方面不像现在的 C++ 那样严格。 This allows for this:这允许:

 char*       p = "Hello";    // Because there is an auto conversion
                             // the compiler is allowed to make 
                             // the conversion from one type to another

Note in later versions of C++ this conversion has been deprecated.请注意,在更高版本的 C++ 中,此转换已被弃用。 SO the compiler will warn you that this is dangerous (because you have removed the const from the type you are allowed to modify it, but the underlying object can't be modified so if you try it will blow up the program).所以编译器会警告你这是危险的(因为你已经从允许修改它的类型中删除了 const,但是底层对象不能被修改,所以如果你尝试它会炸毁程序)。

So why can you assign char const to a char ?那么为什么可以将char const分配给char呢?

char  x = 'X';

Here you are copying the original object char const into an object of type char this is perfectly valid.在这里,您将原始对象char const复制到一个完全有效的char类型对象中。 You can not alter or chance the literal but you are allowed to make copies of it.你不能改变或碰巧文字,但你可以制作它的副本。 So you can easily remove the outer const in an assignment expression.因此,您可以轻松删除赋值表达式中的外部const

 char const* const y = "Hello";
 char const*       z = y;        // We remove the outer const
                                 // from a pointer. But the inner
                                 // const (of the object being pointed
                                 // at) can not be removed so easily.

                                 // This works because z is allowed to 
                                 // to be changed but hold a value a pointer
                                 // to a value that can not be changed.

Looking at your comment:看了你的评论:

#include <iostream>
void test(char *str)
{
    std::cout << str << std::endl;
}

int main()
{
    test("Hello");           // This is allowed in C++
                             // Deprecated still means valid.
                             // Just not a good idea

                             // There is a allowed conversion from
                             // char const* to char* for string literals.


    char const* x = "test";
    test(x);                 // This is NOT allowed.
                             // You can not cast away this const.
}

Note: Technically a string literal is char const[] .注意:从技术上讲,字符串文字是char const[] ie an array of const char.即常量字符数组。 BUT when used in an expression arrays very easily decay into pointers and thus it is sometimes simpler to think of them as char const* but this thinking is abstract and you should know the underlying exact type.但是当在表达式数组中使用时很容易衰减为指针,因此有时将它们视为char const*更简单,但这种想法是抽象的,您应该知道底层的确切类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM