Dav*_*vid 2 c struct function parameter-passing
我在Visual C++中编写的程序存在以下问题,希望有人能帮助我:
typedef struct spielfeld
{
 int ** Matrix;
 int height; 
 int width; 
 Walker walker;
 Verlauf history;
} Spielfeld;
void show(Spielfeld fieldToShow); //Prototype of the Function where I have this
                                  //problem
int main(int argc, char *argv[])
{
  int eingabe;
  Spielfeld field;
  //Initialize .. and so on
  //Call show-Function and pass the structure with Call by Value
  show(field);
  //But what's happened? field.Matrix has changed!!
  //can anyone tell me why? I don't want it to become changed!
  //cause that's the reason why I pass the field as Call by Value!
}
void show(Spielfeld fieldToShow)
{
 //Here is the problem: Alltough the parameter fieldToShow has been passed
 //with call by value, "fieldToShow.Matrix[0][0] = 1" changes the field in 
 //main!!
 fieldToShow.Matrix[0][0] = 1;
 //Another try: fieldToShow.walker.letter only affects the local fieldToShow, 
 //not that field in main! That's strange for me! Please help!
 fieldToShow.walker.letter  = 'v';
}
当您传递结构时,您将按值传递它.但是,其中的矩阵实现为指向int的指针.这些指针是引用,因此当您在函数中修改它们引用的值时,相同的值将由原始结构引用main.
如果要按值传递这些对象,则需要自己进行深层复制,在其中分配新矩阵,并将原始矩阵中的所有值复制到其中.
正如Drew所指出的,在C++中,实现深度复制的首选方法是通过复制构造函数.复制构造函数允许您在按值传递对象时执行深层复制,而无需自己显式复制对象.
如果你还没有为类和构造函数做好准备,你可以简单地编写一个函数Spielfeld copySpielfeld(Spielfeld original)来执行那个深层复制; 它基本上与您在示例中省略的初始化代码相同,除了它将从Spielfeld传入的值中获取值,而不是创建新的Spielfeld.你可以通过你之前调用此field进入show功能,或有show功能做了传递,这取决于你如何想你的API工作的任何说法.