【发布时间】:2016-05-16 23:51:23
【问题描述】:
我正在尝试学习 C++ 中的指针和引用。我有以下程序。
#include <iostream>
using namespace std;
int main() {
// 1st statement / code of block. This portion works fine.
char *str = "A";
cout << str << endl; // it outputs A
cout << *str << endl; // it outputs A
cout << &str << endl; // it outputs 0x23fe40 (memory location)
char **b = &str;
cout << b << endl; // it outputs 0x23fe40 (memory location)
cout << *b << endl; // it outputs A
// 2nd statement / code of block. This portion gives error.
// int *st = 5;
// cout << st << endl;
// cout << *st << endl;
// cout << &st << endl;
// int **c = &st;
// cout << c << endl;
// cout << *c << endl;
return 0;
}
代码在这个阶段运行良好。但我运行第二条语句(我在这里评论),编译器给出以下错误。
Invalid conversion from 'int' to 'int*'
有人能解释一下为什么会这样吗?两个语句几乎相同,唯一的区别是我在第二个语句中使用了数据类型“int”。是不是因为数据类型不同?
【问题讨论】:
-
您希望这种转换如何进行?
-
它适用于 char。为什么我不应该期待它与 int?
-
鉴于您期望与
5一起工作,您可能期望"A"成为char。它不是; IIRC,这是一个const char[2]。 -
我怎样才能使第二条语句起作用?
-
字符串很特别……它就是这样设计的。诠释* x=5; // 5 存在于内存中的什么位置?它没有 - 它必须放在内存中的某个地方并且 addr 返回......这是为字符串完成的;我不知道为什么它没有为其他数据类型完成......它可能是。我不确定它会有多大用处/它的用途是什么。