Int函数参数不能正常工作
int function parameter not working properly
我想在c++中做一些事情,我有一个问题。我有这样的代码:
#include <iostream>
#include <string>
//---MAIN---
using namespace std;
int af1 = 1;
int af2 = 1;
void lettersort(int cnt1) {
cout << "RESULT:" << cnt1 << endl;
cnt1++;
cout << "RESULT WHEN+:" << cnt1 << endl;
cout << "RESULT IN GLOBAL INT:" << af2 << endl;
}
int main()
{
lettersort(af2);
return 0;
}
那么有没有办法让cnt1++
也影响af2
,使其变大呢?我不想直接使用af2++
,因为我有时想使用af1
。
目前您只是通过值将af2
传递给cnt1
,因此对cnt1
的任何更改都严格限于lettersort
函数。为了获得您想要的行为,您需要通过引用传递cnt1
参数。变化:
void lettersort(int cnt1)
:
void lettersort(int &cnt1)
您通过值传递参数。也就是说,将af1
的值复制到lettersort
的局部变量中。然后这个整数被加1,并在函数结束时被处理掉,而不影响原来的af1
。如果您希望该函数能够影响af1
,则应该通过引用传递参数:
void lettersort(int& cnt1) { // Note the "&"
如果我没理解你的问题:
有两种方法可以做到这一点。
-
make lettersort function返回新值,并将其放入af2
int lettersort(int cnt1) { cout << "RESULT:" << cnt1 << endl; cnt1++; cout << "RESULT WHEN+:" << cnt1 << endl; cout << "RESULT IN GLOBAL INT:" << af2 << endl; return cnt1; } int main() { af2 = lettersort(af2); return 0; }
-
通过引用传递值。你可以在这里读到,但通常它是传递一个指向那个值的指针。这意味着无论你对你传递的参数做什么,都会发生在原始的var上。
的例子:
void foo(int &y) // y is now a reference
{
using namespace std;
cout << "y = " << y << endl;
y = 6;
cout << "y = " << y << endl;
} // y is destroyed here
int main()
{
int x = 5;
cout << "x = " << x << endl;
foo(x);
cout << "x = " << x << endl;
return 0;
}
- 这里你只需要修改参数传递给lettersort
-
例如,如果您声明并初始化任何变量,如:
int a=10; int &b = a;
-
现在a和b指向相同的值。如果你改变a,那么
-
,
cout << a; cout << b;
-
两个语句在整个程序中产生相同的结果。所以使用这个概念我修改了函数参数,把它写成by参考。
-
你的正确代码是:
#include <iostream> #include <string> using namespace std; int af1 = 1; int af2 = 1; void lettersort(int &cnt1) { cout << "RESULT:" << cnt1 << endl; cnt1++; cout << "RESULT WHEN+:" << cnt1 << endl; cout << "RESULT IN GLOBAL INT:" << af2 << endl; } int main() { lettersort(af2); return 0; }
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 为什么STD ::计数将常数传递给Lambda,而不是在弦上工作时而不是字符
- sdl软件渲染器不工作,工作在硬件加速的一个
- C++程序已停止工作-求解常微分方程