前向变迁改变功能行为
Forward decleration changes function behaviour?
我正在学习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++ 按值传递,除非您在函数参数前面使用 amperstand (&),如下所示:
function swap(int &a, int &b) {
swap
的实现在函数中本地交换值,因为它的参数是按值传递的。它不会更改调用函数中的任何内容。
当您没有该函数声明时,将使用std::swap
,这执行正确的操作。
首先,你的交换函数不会交换原始参数。它交换原始参数的副本,这些参数将在退出函数后销毁。如果您希望函数确实会交换原始参数,则必须将参数声明为引用
void swap(int &a, int &b) {
int tmp = a;
a = b;
b = tmp;
}
当程序中没有函数的前向声明时,编译器似乎选择了交换原始参数的标准函数std::swap
。由于 using 指令,编译器会考虑标准函数std::swap
using namepsace std;
如果删除它并删除函数的前向声明,则编译器将发出错误。
当函数的前向声明存在时,编译器会选择您的函数,因为它与非模板函数最匹配。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 变量没有改变?通过向量的函数调用
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 文件系统:复制功能的速度秘诀是什么
- 链接列表加法/减法功能正在改变参数的值
- C++ SDL 功能在首次启动后似乎不会改变主表面
- 前向变迁改变功能行为
- 当我改变他的背景时,我失去了按钮的功能
- 在不改变接口的情况下为对象增加功能