#include<iostream>
using namespace std;
int main()
{
int*p=new int;
if(p!=NULL)
{
int&r=*p;
r=3;
}
cout<<"*p:"<<*p<<"\n";
return 0;
}
运行正常
然后我稍微改一下,把r=3;放在if语句块下一句,理论上运行结果应该是一样的啊,如下
#include<iostream>
using namespace std;
int main()
{
int*p=new int;
if(p!=NULL)
{
int&r=*p;
}
r=3;
cout<<"*p:"<<*p<<"\n";
return 0;
}
结果提示错误:
D:\C++实验\引用还是指针.cpp(10) : error C2065: 'r' : undeclared identifier
执行 cl.exe 时出错.
哪位大神解释一下这两种写法有啥不同?