【发布时间】:2021-09-22 21:04:31
【问题描述】:
我目前正在编写一个函数,该函数必须更新布尔值。
但出于某种原因,它并没有这样做。让我给你看一个简化的版本:
main.cpp
#include <iostream>
#include "header.h"
int main(){
bool limit = true;
test(limit);
if (limit == false){cout << "hi";}
}
header.h
void test(bool x);
header.cpp
#include <iostream>
#include "header.h"
void test(bool x){
x = false;
}
我在主函数中定义了布尔“限制”。然后我将它传递给位于 header.cpp 中的函数“test”。在此函数中,布尔限制设置为 false。 但是,返回到 main.cpp,布尔值仍然是正确的。我看到了,因为没有调用 if 条件。 我怀疑该错误与文件之间传递的信息有关。 你知道真正的原因和可能的替代方案吗?
【问题讨论】:
-
检查“按值传递”和“按引用传递”。这是 C++ 编程的非常基本原则。
标签: c++ function linker header boolean