首页 > 解决方案 > 当 CLASS 按值传递给方法时,为什么 CLASS 中的值会发生变化?

问题描述

这个问题是使用类而不是结构来传递给方法......它会以这种方式改变结果。


#include "pch.h"  //header from MSVS c++ console app
#include <iostream>



class C_PetList
{
public:
  double *mpdVal;

  C_PetList()
  {
    mpdVal = new double[20];
  }

  ~C_PetList() //Placing the destructor in here gives the same results from my other code.  All my values are set to -1.4568159901474629e+144

  {
    if (mpdVal)
    {
      delete mpdVal;
      mpdVal = nullptr;
    }
  }
};

class C_Pet
{
public:
  C_Pet() {}

  ~C_Pet() {}


  void EvalPetList(C_PetList c_PetList)
  {
    // do something
    for (int i = 0; i < 20; i++)
    {
      c_PetList.mpdVal[i] += 300;
    }
  }

  void ProcessPetList(C_PetList c_PetList)
  {

    EvalPetList(c_PetList); //passed by value
  }
};

int main()
{
  C_Pet c_Pet;

  C_PetList c_PetList;

  for (int i = 0; i < 20; i++)
  {
    c_PetList.mpdVal[i] = (double)i;
  }

  c_Pet.ProcessPetList(c_PetList);
}

标签: c++

解决方案


推荐阅读