我对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;
}