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

Why C++ member function uses & in argument?

本文关键字:in 参数 C++ 成员 函数 为什么      更新时间:2023-10-16

可能重复:
如何在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;
}

此代码有效。但在我看来,b->isSelf(a)实际上应该是b -> isSelf(&a),因为isSelf需要类型为C的地址?!

[编辑]附加问题:

1) 有没有一种方法可以使用传递值来实现这个isSelf函数?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;
}

之间存在差异

bool C::isSelf (C& param)  // pass by 'reference'
               ^^^

bool C::isSelf (C* param)  // pass by 'address'
               ^^^

因此,在第二个版本中,C对象(即C*)的地址是预期的,而不是在第一个版本中。

还应注意,内部第1版和第2版可能会以类似方式实施;但是存在语法差异。有第三个版本:

bool C::isSelf (C param)  // pass by value
               ^^^

对于编辑后的问题:

1) 有没有一种方法可以使用传递值来实现这个isSelf()函数?

不可能满足您的特定要求。因为它创造了一个新的价值,而这个价值永远不会匹配。从代码中删除传递值版本。

除此之外,通常情况下,对于任何函数,您都应该选择按值传递通过引用传递

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);
}

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

Q:但在我看来,b->isSelf(a)实际上应该是b->isSelf(&a)

A: 是的,"addressof"操作符(&)就是这样工作的。但这是一个参考参数

查看此链接中的示例:

http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/

void foo(int &y) // y is now a reference
{
    using namespace std;
    cout << "y = " << y << endl;
    y = 6;
    cout << "y = " << y << endl;
} // y is destroyed here
int main()
{
    int x = 5;
    cout << "x = " << x << endl;
    foo(x);
    cout << "x = " << x << endl;
    return 0;
}

PS:

以下是上面的样本输出:

x = 5
y = 5
y = 6
x = 6

在函数声明中,参数名称前的"与"号表示通过引用传递。在C中,这只能通过指针来实现。不过,通过引用传递,调用方不需要知道参数是通过引用传递的,只需正常使用对象即可。

&字符同时用于的地址和引用参数声明,这只是一个不幸的巧合。请记住,地址传递是这样声明的:int isSelf(C *other);

函数签名中的&意味着该值将作为Alias传递,也就是说,它将是原始变量的确切内存位置。

这与传递地址略有不同,在传递地址中,参数类型本身是指向您的类型的指针,而不是确切的类型。

在C++中,具有类似C& param的参数的函数通过引用而不是值来传递它。这类似于通常传递指向函数的指针的方式,但有助于防止指针操作中的一些常见错误。

你可能想看看这个链接的开头:http://www.cplusplus.com/doc/tutorial/functions2/

当通过引用传递变量时,我们不会传递它的值,但我们以某种方式将变量本身传递给函数和我们对局部变量所做的任何修改在中作为参数传递的对应变量中具有效果对函数的调用。