c++ - 从 C++ 返回对对象的引用时,是否需要在返回变量中使用 "&"运算符?

标签 c++

假设我有以下代码:

#include <iostream>

using namespace std;

class Account
{
private:
    float balance;

public:
    Account() { balance = 0.0; };
    float GetBalance() { return balance; };
    void SetBalance(float newBalance) { balance = newBalance; };
};

Account mainAccount;

Account& GetAccount()
{
    return mainAccount;
}

void PrintAccountInfo()
{
    cout << "mainAccount's balance is " << mainAccount.GetBalance() << endl;
}

int main()
{
    PrintAccountInfo();
    Account &a = GetAccount(); // Line 31
    a.SetBalance(30.0);
    PrintAccountInfo();
    return 0;
}

当我运行它时,我得到以下输出(如预期的那样):

mainAccount's balance is 0
mainAccount's balance is 30

但是,在第 31 行,如果我把“Account &a”中的“&”去掉,就变成这样:

Account a = GetAccount(); // note lack of "&"

我得到这个输出:

mainAccount's balance is 0
mainAccount's balance is 0

怎么会?我想在返回引用时,“&”是多余的/不是必需的?我是否从根本上误解了引用在 C++ 中的工作方式?

编辑:谢谢,我现在明白为什么两者不同了。但是,我不应该这样做吗:

Account GetAccount()
{
    return mainAccount;
}

int main()
{
    Account &a = GetAccount();
    // ....
}

但是,当我运行它时,出现错误:

untitled: In function ‘int main()’:

untitled:31: error: invalid initialization of non-const reference of type ‘Account&’ from a temporary of type ‘Account’

最佳答案

I thought when returning a reference, the "&" is redundant / not necessary?

你想错了。

考虑这两行:

Account &a = GetAccount(); // Line 31

Account a = GetAccount(); // Line 31

首先,您声明一个名为 a 的引用,它绑定(bind)到函数 GetAccount 返回的对象。

第二,您声明一个对象 a,它由函数 GetAccount 返回的对象复制初始化。

从根本上说:一个声明一个引用,另一个声明一个对象。


编辑:回答后续问题:

"can I remove the & from the return type in the declaration of the GetAccount function: Account GetAccount() { return mainAccount; }"

您当然可以删除&,但是您的行为将会改变。考虑这两个函数:

Account GetAccount() { return mainAccount; }

Account &GetAccount() { return mainAccount; }

首先,您返回一个临时对象,该对象已从 mainAccount 对象复制初始化。在第二个中,您返回对 mainAccount 对象的引用。

  • 如果您希望 a 成为对 mainAccount 的引用,您需要在这两个地方都使用 &

  • 如果您希望amainAccount 的拷贝,则在a 的声明中不需要& 。其他声明在这种情况下无关紧要。

  • 如果您希望 a 成为对编译器生成的临时值的引用(提示:您不需要),请使用 声明 a &,但 GetAccount 没有。

关于c++ - 从 C++ 返回对对象的引用时,是否需要在返回变量中使用 "&"运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12307796/

相关文章:

c++ - 将对基类的引用传递给 boost::thread,并调用派生类中的虚函数是否可行?

c++ - 从没有sstream c++的字符串中提取整数

c++ - Lapack 例程 dstev 中的段错误

c++ - 如何从 Visual Studio 2017 社区版 C++ 项目导出 DLL?

c++ - 为什么我不能在 C++ 中使用不同的指针访问 int?

c++ - shared_ptr 构造函数参数是否应该按值传递

c++ - 强制 WSARecv 重叠

c++ - 如何将 std::string 转换为 wchar_t*

c++ - 使用右值/左值理解模板参数推导

c++ - 在 Arduino 中编程时避免使用指针和#defines?