首页 > 不同类型的常量指针指向非常量对象时,为什么不行,引用却可以?

不同类型的常量指针指向非常量对象时,为什么不行,引用却可以?

首先引用是可以的,比如:

main()
    {
     double a=34.24;
     const int &b=a;
     std::cout<<b;
     return 0; 
    }

输出为34。过程是:

double a=43.24;
int temp=a;
const int &b=temp;

过程产生了临时量,可是使用指针的时候为什么不可以呢?

main()
{
  double a=34.24;
  const int *b=&a;
  std::cout<<*b;
  return 0;
}

这里为什么不会产生临时量呢?临时量的产生有一条不是:为了使函数成功调用而进行隐式类型转换。
更新:
貌似指针不会生成临时量,但是指针可以指向临时量,如下:

int main()
 {
     double a = 34.24;
    
    const int  &c = a;
    const int *const b = &c;
    a = 435.35;
     std::cout << *b;
     
system("pause");
}

指针不会隐式转换,需要自己去转换。

double a = 34.24;
const int *b = (int*)&a;
std::cout << *b;
【热门文章】
【热门文章】