为什么C++成员函数在参数中使用&?

qaz*_*wsx 0 c++ pointers class

可能重复:
如何将对象传递给C++中的函数?
运算符&和*在类中的函数原型

#include <iostream>
using namespace std;

class C {
  public:
    int isSelf (C& param);
};

bool C::isSelf (C& param)
{
  if (&param == this) return true;
  else return false;
}

int main () {
  C a;
  C* b = &a;
  cout << boolalpha << b->isSelf(a) << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这段代码有效.但在我看来 b->isSelf(a)应该真的是b -> isSelf(&a)因为isSelf期望一个类型的地址C?!

[编辑]其他问题:

1)有没有办法isSelf使用pass by value 实现这个功能?2)实现是否通过引用传递并通过指针传递正确?

bool C::isSelf1(const C &c)
{
    if (&c == this) {
        return true;
    } else {
        return false;
    }
}

bool C::isSelf2(C c)
{
    if (&c == this) {
        return true;
    } else {
        return false;
    }
}

bool C::isSelf3(C * c)
{
    if (c == this) {
        return true;
    } else {
        return false;
    }
}

int main ()
{
    C c1 (2);
    C * c2 = &c1;
    cout << boolalpha;
    cout << c2 -> isSelf1(c1) << endl; // pass by reference
    cout << c2 -> isSelf2(c1) << endl; // pass by value
    cout << c2 -> isSelf3(&c1) << endl;// pass by pointer
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

iam*_*ind 6

有以下区别:

bool C::isSelf (C& param)  // pass by 'reference'
               ^^^
Run Code Online (Sandbox Code Playgroud)

bool C::isSelf (C* param)  // pass by 'address'
               ^^^
Run Code Online (Sandbox Code Playgroud)

所以在第二版本中,C对象(即C*)的地址是预期的而不是第一版.

另请注意,内部第1版和第2版可能类似地实现; 但是有一个语法差异.有第3版:

bool C::isSelf (C param)  // pass by value
               ^^^
Run Code Online (Sandbox Code Playgroud)

编辑问题:

1)有没有办法isSelf()使用pass by value 实现这个功能?

不符合您的要求.因为它创建了一个永远不会匹配的新值.从代码中删除版本的传递.

除此之外,对于任何函数,通常您应该选择按值传递通过引用传递.你不能同时拥有它们,因为它们的函数调用语法都是相同的,这将导致歧义.

2)实现是否通过引用传递并通过指针传递正确?

它们是正确的,但您可以将它们简化为:

bool C::isSelf(const C &c) const // don't give postfix '1', simply overload
{                          ^^^^^
  return (&c == this);
}

bool C::isSelf(C* const c) const // don't give postfix '3', simply overload
{                          ^^^^^
  return (c == this);
}
Run Code Online (Sandbox Code Playgroud)

另外,请参阅执行此类操作的const correct-ness语法.