相关疑难解决方法(0)

相同内存地址的两个不同值

#include <iostream>
using namespace std;

int main() {
    const int N = 22;
    int * pN = const_cast<int*>(&N);
    *pN = 33;
    cout << N << '\t' << &N << endl;
    cout << *pN << '\t' << pN << endl;
}
Run Code Online (Sandbox Code Playgroud)

产量

22 0x22ff74

33 0x22ff74

为什么同一地址有两个不同的值?

c++

16
推荐指数
3
解决办法
1740
查看次数

为什么它不会在我的代码中更改const对象?

这是代码

int main()
{   
  const int i = 2;
  const int * pi = &i;
  int* j = const_cast<int *> (pi);
  *j = 11;
  std::cout << *pi << std::endl;
  std::cout << i << std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

结果:

11

2 <---为什么?

c++

3
推荐指数
1
解决办法
62
查看次数

包含const_cast的代码片段的说明

int main() {
  const int i =10;
  int *j = const_cast<int*>(&i);
  cout<<endl<<"address of i "<<&i;
  cout<<endl<<"value of  j "<<j;
  (*j)++;
  cout<<endl<<"value of  *j "<<*j;
  cout<<endl<<"value of i "<<i;
  // If Not use Const //
  int k = 10;
  int *p = &k;
  cout<<endl<<"address of k "<<&i;
  cout<<endl<<"address of p "<<&p;
  (*p)++;
  cout<<endl<<"value of  *p "<<*p;
  cout<<endl<<"value of  k  "<<k<<endl;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

地址i0xbf8267d0
j0xbf8267d0
*j11 地址
i10
地址k0xbf8267d0
地址p0xbf8267c8 …

c++ c++11

0
推荐指数
1
解决办法
83
查看次数

标签 统计

c++ ×3

c++11 ×1