交换功能 - 指针 - 混淆

时间:2016-11-22 09:54:34

标签: c++ c pointers

请注意代码中我没有使用指针,但我有一些概念,如果我使用这个函数,当代码块完成时,该值将恢复正常。

但代码正在编译,实际上我会用指针得到答案。

我需要帮助,因为如果我有与指针相关的犯规概念,我会感到困惑。

void swap(int i, int j) {
    int temp = i;
    i = j;
    j = temp;
}

int main() {
    int a = 110;
    int b = 786;
    cout << "Before swapping the value" << endl;
    cout << "'a' stores the value : " << a << endl;
    cout << "'b' stores the value : " << b << endl;
    swap(a,b);
    cout << "\nAfter swapping the value" << endl;
    cout << "'a' stores the value : " << a << endl;
    cout << "'b' stores the value : " << b << endl;
    swap(a, b);
    cout << "\nAnd back again swapping the value" << endl;
    cout << "'a' stores the value : " << a << endl;
    cout << "'b' stores the value : " << b << endl;

    return 0;
}

I am getting results without using pointers - is this IDE problem

3 个答案:

答案 0 :(得分:6)

您的swap函数不会交换main范围内的值,因为ij函数局部变量。为了获得您期望的行为,您应该通过引用传递。

void swap(int& i, int& j) {
    int temp = i;
    i = j;
    j = temp;
}

您的代码将not actually swap the values

<强>猜测
我认为您是using namespace std;,并且来自您与std::swap发生冲突的标准库中的#include。我认为在您的情况下调用函数的std::版本,这是您的代码看起来“工作”的唯一原因。

答案 1 :(得分:3)

您所包含的iostream标头似乎还包含utility标头;并且你得到了std::swap的定义。

由于您(不要显示,但可能)代码中有using namesapce std;,因此swap的重载包含两个重载。根据重载决策的规则,调用正确的 1 重载。

1 对于某些正确的定义,在本例中为

答案 2 :(得分:0)

如果你想使用指针交换,你应该通过指针传递:

void swap(int *a, int*b)
{
  int temp = *a;
  *a = *b;
  *b = temp;
}
另一个用户指出,

通过引用传递是另一种选择。

PS:您的查询与函数指针无关,因此我将从查询中删除函数指针标记。