如果我们通过开始'&'来声明一个char变量会发生什么?在C ++中?

时间:2017-05-06 13:41:17

标签: c++ variables character

我想知道字符变量名称的简短区别,例如以'&'开头。并以如下字母开头:

char &c = 'a'; char a = 'a';

变量& c和a。

之间的短暂区别是什么

1 个答案:

答案 0 :(得分:1)

我可以保证您的编译器会拒绝char &c = 'a'; 在C ++中,您还可以为现有变量或函数定义引用,而不是定义指针​​(char *c = &a)。通过在引用名称前添加&符号来定义引用。与指针区分,引用必须引用给定变量。此外,一旦定义了引用,就无法更改它。请参阅以下示例。

// I'll use char in the examples
char a = 'a', aa = 'z';
char *b1 = &a;  // OK, defines pointer b1 pointing to a
char *b2;       // OK, defines pointer b2 but not assigning an address
char &c1 = a;   // OK, c1 is a reference to a
char &c2;       // Wrong. A reference must have a referee
char &c3 = 'c'; // Wrong. Referee must be LHS
int x = 0;
char& c3 = x;   // Wrong. c3 and x type must match

// b1 is of type "char*", c1 is of type "char&", effectively the same as "char"
a = 'd'; cout << *b1 << c1; // Output: dd
*b1 = 'e'; cout << a << c1; // Output: ee
cout << sizeof(a) << " " << sizeof(b1) << " " << sizeof(c1);
                            // Output: 1 4 1 (or "1 8 1" on a 64-bit system)
b1 = &aa; cout << *b1;      // Output: z
&c1 = aa;                   // Wrong. Can't reassign references
c1 = aa; cout << c1;        // Output: z (Seems OK)
cout << a;                  // Output: z (Oops, original a is also changed)