gpt4 book ai didi

c++ - C++中的因变量?

转载 作者:可可西里 更新时间:2023-11-01 18:05:35 26 4
gpt4 key购买 nike

我之前问过,但我不是很清楚,所以我重新问了。

我想要一个依赖于另一个变量值的变量,比如这个例子中的 b:

int main(){
int a;
dependent int b=a+1; //I'm just making this up
a=3;
cout << b; //prints 4
a=4;
cout << b; //prints 5
}

当然,这在C++中是不存在的,但这是我想要的。

所以我尝试创建一个函数:

int main(){
int a;
int b(){ return a+1; } //error
a=3;
cout << b(); //would print 4 if C++ allowed nested functions
a=4;
cout << b(); //would print 5 if C++ allowed nested functions
}

上面的代码不起作用,因为 C++ 不允许嵌套函数。

我只能在 main() 之外创建函数,如下所示:

int b(){
return a+1; //doesn't work because a is not in scope
}

int main(){
int a;
a=3;
cout << b();
a=4;
cout << b();
}

但这不起作用,因为 a 与 b() 不在同一范围内,所以我必须将 a 作为参数传递,但我不想这样做。

是否有任何技巧可以使 C++ 中的因变量变得类似?

最佳答案

您需要的是 closure .如果您可以使用 C++ 0x 功能,那么您很幸运。否则,您可以手动定义一个:

#include <iostream>
using namespace std;
struct B
{
const int & a;

B(const int & a) : a(a) {}

// variable syntax (Sean Farell's idea)
operator int () const { return a + 1; }

// function syntax
int operator () () const { return a + 1; }
};
int main()
{
int a;
B b(a);
a = 3;
cout << b << '\n'; // variable syntax
a = 4;
cout << b() << '\n'; // function syntax
}

您也可以在 main 中定义 B,但有些编译器不喜欢它。

C++ 0x lambda语法如下所示:

auto b = [&]() { return a + 1; }

[&] 表示 lambda 通过引用捕获局部变量。

关于c++ - C++中的因变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6868993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com