首页 > 解决方案 > 在 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.t​​heProfile 与测试不一样?据我了解,theProfile 是 (*aProflie) 的引用,aProfile 是指向测试对象的指针,这意味着它们共享一个相同的地址。如果这个地址中的 test 发生了变化,为什么 test.test 没有变成 2?

谁能帮我理解这一点?谢谢!

标签: c++

解决方案


this指向调用对象的指针。因此,为了分配给对象,this必须取消引用指针。构造函数按值Asset获取 Profile 指针,当它被取消引用以传递给构造函数时,被指向的对象通过引用传递。Profile


推荐阅读