c++ - 当 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);
}
解决方案
推荐阅读
- python - Python 函数如何在它的参数被这样评估之前变得有效?
- asp.net-core - 跨存储过程调用的 Asp.Net 实体框架核心事务
- git - 命令行 - GitHub 存储库错误:似乎不是 git 存储库
- ruby - 跳过 RSpec 中的多个示例?
- angular - 如何延迟加载角核心模块(FormsModule)
- sql - 在 SQL 中转换的 Excel 5 位日期时间提前 2 天
- swift - 如何通过 id Swift 获取数据
- mysql - 使用 bash 的 mysql 数据库复制脚本
- sql - 基于 IS_MEMBER 函数的行级安全性
- c# - 使用 DownloadUrl 在 C# 中下载文件