c++ - 在 C++ 中按引用调用或按值调用
问题描述
我是 C++ 初学者,我了解按引用或值调用的基本概念。但在以下情况下,我对这个调用是引用还是值感到困惑。我正在阅读其他人的代码,我通过削减其他逻辑来简化它,只保留显示它是通过引用还是值调用的逻辑。
这是代码
class Profile
{
public:
int test = 1;
Profile() {}
Profile(const Profile& original) // create a reference original and then assign the object (*aProfile) to it
{
*this = original;
}
void change()
{
test = 2;
}
};
class Asset
{
public:
Profile theProfile;
Asset() {}
Asset(Profile *aProfile) // aProfile should be a pointer points to Profile
{
theProfile = Profile(*aProfile); // create another object by (*aProfile)
theProfile.change();
}
};
int main() {
Profile test; // create the object test
Asset a(&test); // take the address of test as argument
}
我的问题是为什么 a.theProfile 与测试不一样?据我了解,theProfile 是 (*aProflie) 的引用,aProfile 是指向测试对象的指针,这意味着它们共享一个相同的地址。如果这个地址中的 test 发生了变化,为什么 test.test 没有变成 2?
谁能帮我理解这一点?谢谢!
解决方案
this
是指向调用对象的指针。因此,为了分配给对象,this
必须取消引用指针。构造函数按值Asset
获取 Profile 指针,当它被取消引用以传递给构造函数时,被指向的对象通过引用传递。Profile
推荐阅读
- javascript - 如何在电子中将目标 URL 与我自己的资源挂钩?
- python - 如何根据分辨率将已经拆分的日期分成两列?
- php - 如何使用 laravel 更改前端的显示布局
- arm - 在运行时检测 arm 处理器上的扩展超截面支持
- python - 如何旋转 matplotlib 图形?
- javascript - 有没有办法从“mysql”数据库中获取数据并在我的 javascript 文件中使用它?
- html - 如何在角度中使用formGroup在选择中设置选项?
- opencv - 如何在 JavaCV 中进行人脸对齐?
- xamarin - 在 Xamarin.Forms 上检索列表视图数据问题
- c# - 在iis中发布时遇到问题,会话变量正在消失(c#)