【发布时间】:2014-10-08 07:35:55
【问题描述】:
对 C++ 很陌生。我见过人们通常在运算符重载中通过引用传递对象。嗯,我不知道什么时候真的有必要。如下面的代码所示,如果我在 operator+ 中删除对象 c1 和 c2 声明中的 & 符号,我仍然会得到相同的结果。当我们不想修改 c1 或 c2 时,在这种情况下是否有任何理由通过引用传递?
#include <iostream>
class Keys
{
private:
int m_nKeys;
public:
Keys(int nKeys) { m_nKeys = nKeys; }
friend Keys operator+(const Keys &c1, const Keys &c2);
int GetKeys() { return m_nKeys; }
};
Keys operator+(const Keys &c1, const Keys &c2)
{
return Keys(c1.m_nKeys + c2.m_nKeys);
}
int main()
{
Keys cKeys1(6);
Keys cKeys2(8);
Keys cKeysSum = cKeys1 + cKeys2;
std::cout << "There are " << cKeysSum.GetKeys() << " Keys." << std::endl;
system("PAUSE");
return 0;
}
【问题讨论】:
-
如果不通过引用(或通过指针)作为参数传递对象,则通过值传递它们,这意味着它们被复制;有些对象的复制成本很高。
-
好吧,如果您使用引用,则无需将对象作为参数复制为一件事,因此将参数作为引用可能会更有效
标签: c++ operator-overloading pass-by-reference