当我编写此代码片段时,在通过指针修改 const 变量 i 的值后,我将 i 的值设为 10,但是当我打印 *ptr 时,我得到 110。
const int i = 10;
int *ptr = const_cast<int *>(&i);
*ptr = *ptr + 100;
cout << "i: " << i << "\t*ptr: " << *ptr << endl;
我得到输出 i: 10 和 *ptr :110。
在这种情况下,我有一个 const 变量 x 作为 Base 类的成员变量。通过函数 show() 我可以修改 const 变量 x 的值,即当我打印 x 和 *ptr 时,我在两者中都得到了改变的值。
class Base
{
public:
const int x;
Base(int i) : x(i) {}
virtual void show()
{
int *ptr = const_cast<int *>(&x);
int *ptr = const_cast<int *>(&x);
cout << "In Base show:\n";
cout << "Address of x : " << &x << endl;
cout << "Address in ptr : " << ptr << endl;
cout << "value in x : " << x << endl;
cout << "value in ptr : " << *ptr << endl;
*ptr = *ptr + 10;
cout << "After modifying " << endl;
cout << "value in x : " << x << endl;
cout << "value in ptr : " << *ptr << endl;
}
};
class Derived : public Base
{
public:
Derived(int i) : Base(i){}
virtual void show()
{
int *ptr = const_cast<int *>(&x);
cout << "In Derived show:\n";
cout << "Address of x : " << &x << endl;
cout << "Address in ptr : " << ptr << endl;
cout << "value in x : " << x << endl;
cout << "value in ptr : " << *ptr << endl;
*ptr = *ptr + 10;
cout << "After modifying " << endl;
cout << "value in x : " << x << endl;
cout << "value in ptr : " << *ptr << endl;
}
};
int main()
{
Base bobj(5),*bp;
Derived dobj(20), *dptr;
bp = &bobj;
bp->show();
bp = &dobj;
bp->show();
return 0;
}
The output which I am getting is this
In Base show:
Address of x : 0x7fff82697588
Address in ptr : 0x7fff82697588
value in x : 5
value in ptr : 5
After modifying
value in x : 15
value in ptr : 15
In Derived show:
Address of x : 0x7fff82697578
Address in ptr : 0x7fff82697578
value in x : 20
value in ptr : 20
After modifying
value in x : 30
value in ptr : 30
任何人都可以帮忙。