带/不带指针的函数原型用法的差异

问题描述

我正在学习简单的C ++教程。

// cloning item with ajax(need to display new item)
$('.cloneItemButton').click(async function () {
    let itemId = $(this).attr('id')
    itemId = itemId.replace('-clone','')
    await cloneItem(itemId)
})


cloneItem = (itemId) => {
    $.ajax({
        method: 'POST',url: '/item/' + itemId + "/clone",success: function (resp) {
            console.log('Item Cloned: ' + resp._id)
            template = `TEMPLATE HERE`
            var html = ejs.render(template,{ item: resp });
            // var html = new EJS({ url: '../../views/itemDisplay.ejs' }).render({ item: resp })
            // $('.inventory-scroll-list').append(html)
            $(html).hide().appendTo('.inventory-scroll-list').fadeIn(300);
        },})
}

上面的代码可以正常工作(g ++和icc),但是如果我要在函数中使用指针,那么如果我不在程序的开头包含原型,代码就会失败。

#include <iostream>
using namespace std;

int main()
{
  int a = 1,b = 2;

  cout << "Before swapping " << endl;
  cout << "a = " << a << endl;
  cout << "b = " << b << endl;

  swap(a,b);

  cout << endl;
  cout << "After swapping " << endl;
  cout << "a = " << a << endl;
  cout << "b = " << b << endl;

  return 0;
}

void swap(int &n1,int &n2)
{
  int temp;
  temp = n1;
  n1 = n2;
  n2 = temp;
}

据我所知,C ++编译过程是自上而下的,因此第二代码似乎更合理,其中在遇到#include <iostream> using namespace std; void swap(int*,int*); // The code fails if I comment this line. int main() { int a = 1,b = 2; cout << "Before swapping" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; swap(&a,&b); cout << endl; cout << "After swapping" << endl; cout << "a = " << a << endl; cout << "b = " << b << endl; return 0; } void swap(int* n1,int* n2) { int temp; temp = *n1; *n1 = *n2; *n2 = temp; } 之前提供函数的信息。我的问题是,即使没有int main()之前的函数知识,为什么第一代码也能正常工作?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)