【问题标题】:Forward decleration changes function behaviour?前向声明改变函数行为?
【发布时间】:2015-03-16 22:01:50
【问题描述】:

我正在学习 C++,只是发现了一些我想理解的奇怪东西(参见代码第 5 行的注释):

#include <iostream>

using namespace std;

// WITH this forward decleration the output is A=1 and B=2
// WITHOUT this forward decleration the output is A=2 and B=1
// WHY??
void swap(int a, int b);

int main() {

    int a = 1;
    int b = 2;

    swap(a, b);

    cout << "A: " << a << endl;
    cout << "B: " << b << endl;

    system("PAUSE");

    return 0;
}

void swap(int a, int b) {
    int tmp = a;
    a = b;
    b = tmp;
}

谁能解释一下这种行为?我认为默认情况下 c++ 按值传递,除非您在函数参数前面使用符号 (&),如下所示:

function swap(int &a, int &b) {

【问题讨论】:

  • 如果您同时删除该指令和 using 指令,它将无法编译,如您所料。
  • @chris 不是真的,std::swap 实现了正确的交换(不像他的)。
  • @0x499602D2,是的,我知道。 Here's what I mean.

标签: c++ visual-studio gcc syntax forward-declaration


【解决方案1】:

swap 的实现会在函数中本地交换值,因为它的参数是按值传递的。它不会改变调用函数中的任何内容。

当您没有该函数声明时,将使用 std::swap,这样做是正确的。

【讨论】:

    【解决方案2】:

    首先,您的交换函数不会交换原始参数。它交换将在退出函数后销毁的原始参数的副本。如果您希望该函数确实会交换原始参数,则必须将参数声明为引用

    void swap(int &a, int &b) {
        int tmp = a;
        a = b;
        b = tmp;
    }
    

    当程序中没有函数的前向声明时,编译器似乎选择了标准函数std::swap 来交换原始参数。由于 using 指令,编译器会考虑标准函数std::swap

    using namepsace std;
    

    如果您删除它并删除函数的前向声明,那么编译器将发出错误。

    当你的函数的前向声明出现时,编译器会选择你的函数,因为它是非模板函数的最佳匹配。

    【讨论】:

    • 与 R Sahu 的答案几乎相同,但提供了更多信息。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多