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

标签 c++ class pointers

<分区>

Possible Duplicate:
How to pass objects to functions in C++?
Operator & and * at function prototype in class

#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) Is there a way to implement this isSelf() function using pass by value?

您的给定要求不可能。因为它创造了一个新的值(value),而且永远不会匹配。从您的代码中删除按值传递版本。

除此之外,通常您应该为任何函数选择按值传递按引用传递。不能同时拥有两者,因为它们的函数调用语法相同,这会导致歧义。

2) Are the implementation using pass by reference and pass by pointer correct?

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

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 语法。

关于c++ - 为什么 C++ 成员函数在参数中使用 &?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8738235/

相关文章:

c++ - 如何显示类中某些内容的枚举值?

PHP类问题

java - 如何调用类/静态方法

c - 带指针的结构体定义

c++ - 在另一个 std::tuple 中创建类型为 "contained"的 std::tuple

C++11 regex_token_iterator

C++析构函数问题

c++ - 他们如何使 "Get Windows 10"图标默认具有 "Show icon and notifications"可见性?

c++ - 弱/强引用指针关系

c - 取消引用双指针时出现问题