【发布时间】:2011-03-11 17:30:50
【问题描述】:
如何在函数 fn 中强制 obj->val1 指向的内存为常量?
#include <iostream>
struct foo {
int* val1;
int* val2;
int* val3;
};
void fn( const foo* obj )
{
// I don't want to be able to change the integer that val1 points to
//obj->val1 = new int[20]; // I can't change the pointer,
*(obj->val1) = 20; // But I can change the memory it points to...
}
int main(int argc, char* argv[])
{
// I need to be able to set foo and pass its value in as const into a function
foo stoben;
stoben.val1 = new int;
*(stoben.val1) = 0;
std::cout << *(stoben.val1) << std::endl; // Output is "0"
fn( &stoben );
std::cout << *(stoben.val1) << std::endl; // Output is "20"
delete stoben.val1;
return 0;
}
这里的代码很容易解释。我需要能够制作一个非常量对象并用数据填充它,然后将其传递给无法修改此数据的函数。我该怎么办?
我知道我可以只传入一个 const int 指针,但从理论上讲,这个类还包含其他几个我在“fn”中也需要的指针。
谢谢,
格里夫
【问题讨论】:
标签: c++ c pointers struct constants