如何在C ++中将指针Foo **转换为const Foo ** [英] How to pointer-cast Foo** to const Foo** in C++
问题描述
我有
class Fred
{
public:
void inspect() const {};
void modify(){};
};
int main()
{
const Fred x = Fred();
Fred* p1;
const Fred** q1 = reinterpret_cast<const Fred**>(&p1);
*q1 = &x;
p1->inspect();
p1->modify();
}
如何做
const Fred ** q1 =& p1
via pointer-casting?
How would it be possible to do the const Fred** q1 = &p1 via pointer-casting?
(我刚刚读过,可能会这样)
(I have just been reading that this might be possible)
感谢您的回答。 const_cast确实对对象起作用。
Thank you for your answers. The const_cast works indeed for objects
#include <iostream>
#include <stdio.h>
using namespace std;
class Fred
{
int a;
public:
Fred(){};
Fred(int a_input)
{
a = a_input;
};
void inspect() const
{
cout << "Inspect called"<< endl;
cout << "Value is ";
cout << a << endl;
};
void modify()
{
cout << "Modify called" << endl;
a++;
};
};
int main()
{
const Fred x = Fred(7);
const Fred* q1 = &x;
Fred* p1 = const_cast<Fred*>(q1);
p1->inspect();
p1->modify();
p1->inspect();
x.inspect();
*p1 = Fred(10);
p1->inspect();
}
给予
Inspect called
Value is 7
Modify called
Inspect called
Value is 8
Inspect called
Value is 8
Inspect called
Value is 10
Inspect called
Value is 10
但是,对于预定义类型,它不起作用:
However, for predefined types it does not work:
int main()
{
const double a1 = 1.2;
const double* b1 = &a1;
cout << "a1 is " << (*b1) << endl;
cout << "b1 is " << b1 << endl;
double* c1 = const_cast<double*>(&a1);
cout << "b1 is " << b1 << endl;
cout << "c1 is " << c1 << endl;
double* d1 = static_cast<double*>(static_cast<void*>(c1));
cout << "d1 is " << d1 << endl;
cout<< "*d1 is " << *d1 << endl;
*d1=7.3;
cout<< "*d1 is " << *d1 << endl;
cout<< "*d1 address is "<< d1 << endl;
cout << "a1 is " << a1 << endl;
cout << "a1 address is" << &a1 << endl;
cout<< "*d1 is " << *d1 << endl;
cout<< "*d1 address is "<< d1 << endl;
double f1=a1;
printf("f1 is %f \n", f1);
}
导致:
a1 is 1.2
b1 is 0xffbff208
b1 is 0xffbff208
c1 is 0xffbff208
d1 is 0xffbff208
*d1 is 1.2
*d1 is 7.3
*d1 address is 0xffbff208
a1 is 1.2
a1 address is0xffbff208
*d1 is 7.3
*d1 address is 0xffbff208
f1 is 1.200000
显然,g ++编译器会优化,它,所以,即使它的值在堆栈上已经改变,它不在乎。
Apparently the g++ compiler optimizes such that it replaces a1 by 1.2 whenever it finds it, so, even if its value on the stack has changed, it does not care.
(在我的例子中,我遇到了直接读取* b1,* c1的问题,所以我不得不做双静态转换 - 重新解释转换没有工作)。
(In my case I had problems with directly reading the *b1, *c1, so I had to do the double static cast - the reinterpret cast did not work).
这是真正改变a1,编译正常的任何方式,因此没有优化没有编译(所以我超过了优化效果)?
Is it any way to really change a1, compiling "normally", therefore not compiling without the optimization (so I overtake the optimization effect)?
推荐答案
您希望 const_cast
。
这篇关于如何在C ++中将指针Foo **转换为const Foo **的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!