【发布时间】:2016-01-05 04:58:20
【问题描述】:
int &y=x和int y=&x一样吗?s++和*s++一样吗?-
同样在下面的代码中,为什么
*s++给了我一些错误的结果?我期待
*s的值为 12
#include <iostream>
using namespace std;
int main()
{
int p=10;
int &q=p; //q is a reference variable to p
//int r=&p; //error: invalid conversion from 'int*' to 'int'
int *s=&p; //valid
q++;
*s++; //here even s++ works, and cout<<*s does not give 12 but some lengthy number
//and cout<<s gives some hexadecimal, I'm guessing thats the address
cout<<p<<endl<<q<<endl<<*s;
}
我得到的输出:
11 11 6422280【问题讨论】:
-
r=&p给你一个错误的原因是因为你声明了一个int,这意味着你告诉编译器,“嘿,我要在内存中存储一个整数。”但不是给它一个整数,而是给它一个存储整数的地址。这是类型不匹配。编译器试图将其隐式转换为 int,但地址看起来与 int 完全不同。因此出现错误。 -
这些是要问的特殊问题。 1. 由于一个是错误而另一个不是,它们不可能相同。 2. 效果不一样,不可能一样。