Gri*_*fin 8 c c++ struct pointers const
如何在函数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;
}
Run Code Online (Sandbox Code Playgroud)
这里的代码非常自我解释.我需要能够创建一个非const对象并用数据填充它,然后将其传递给无法修改此数据的函数.我怎么能这样做?
我知道我可以传入一个const int指针,但理论上,这个类还包含其他几个指针,我也需要在"fn"中使用.
谢谢,
格里夫
我不是 C++ 人员,但在 C 中,我会通过两种不同的结构声明来处理这个问题,一种是公共的,一种是私有的:
\n\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct private_foo {\n int* val1;\n int* val2;\n int* val3;\n};\n\nstruct public_foo {\n int const * const val1;\n int const * const val2;\n int const * const val3;\n};\n\n\nvoid fn( struct public_foo * obj )\n{\n int local;\n *(obj->val1) = 20; // compile error\n obj->val1 = &local; // compile error\n}\n\nint main(int argc, char* argv[])\n{\n // I need to be able to set foo and pass its value in as const into a function\n struct private_foo stoben;\n stoben.val1 = malloc(sizeof(int));\n if (!stoben.val1) { return -1; }\n *(stoben.val1) = 0;\n printf("%d", *(stoben.val1) );\n fn( (struct public_foo *) &stoben );\n printf("%d", *(stoben.val1) );\n free(stoben.val1);\n return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n当我尝试使用 GCC 编译上述内容时,出现以下编译器错误,因为我正在尝试修改只读内存:
\n\ntemp.c: In function \xe2\x80\x98fn\xe2\x80\x99:\ntemp.c:20: error: assignment of read-only location\ntemp.c:21: error: assignment of read-only member \xe2\x80\x98val1\xe2\x80\x99\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
4038 次 |
最近记录: |