变量不能在 lambda 中隐式捕获,并且没有使用 switch 语句指定捕获默认值



我正在尝试将名称转换为数字。 我的问题是,当我尝试在switch语句中执行简单的a=a+1时,我收到错误消息"变量'a'无法在未指定捕获默认值的lambda中隐式捕获">

在这里寻找相同的错误消息,我发现我应该使用[][=][&]. 我的问题似乎更多的是如何以及在哪里这样做。 如果我[](int a=0){};初始化变量的地方,那么我的消息是" 错误:使用未声明的标识符'a'">

这是我问题的代码

#include <jni.h>
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
static int nameToNumber(string fn, string ln)
{
string nameOne = fn;
string nameTwo = ln;
[](int a=0){};
int b = 0;
int num = 0;
for_each(nameOne.begin(), nameOne.end(), [](char &c )
{
c=::toupper(c);
switch (c){
case 'A':
case 'J':
case 'S': a=a+1;
break;
case 'B':
case 'K':
case 'T': a=a+2;
break;
case 'C':
case 'L':
case 'U': a=a+3;
break;
case 'D':
case 'M':
case 'V': a=a+4;
break;
case 'E':
case 'N':
case 'W': a=a+5;
break;
case 'F':
case 'O':
case 'X': a=a+6;
break;
case 'G':
case 'P':
case 'Y': a=a+7;
break;
case 'H':
case 'Q':
case 'Z': a=a+8;
break;
case 'I':
case 'R': a=a+9;
break;
default: a=a+0;
}
});

for_each(nameTwo.begin(), nameTwo.end(), [](char &c)
{

c=::toupper(c);
switch (c){
case 'A':
case 'J':
case 'S': b=b+1;
break;
case 'B':
case 'K':
case 'T': b=b+2;
break;
case 'C':
case 'L':
case 'U': b=b+3;
break;
case 'D':
case 'M':
case 'V': b=b+4;
break;
case 'E':
case 'N':
case 'W': b=b+5;
break;
case 'F':
case 'O':
case 'X': b=b+6;
break;
case 'G':
case 'P':
case 'Y': b=b+7;
break;
case 'H':
case 'Q':
case 'Z': b=b+8;
break;
case 'I':
case 'R': b=b+9;
}
});
num = a + b;
if ((num > 9) && (num != 11) && (num != 22) && (num != 33))
{
//add both digits together to get a single digit
a=0;
b=0;
a = num / 10; //get first digit
b = num % 10; //get second digit
num = a + b; //add them together
}
return num;
}

这就是我称之为的地方

extern "C" JNIEXPORT jstring JNICALL
Java_com_sezju_namenumerology_MainActivity_transformInfo(
JNIEnv *env,
jobject /* this */,
jstring fName,
jstring lName,
jint age) {
int luckynum = nameToNumber(jstringToString(env, fName), jstringToString(env, lName));
string message = jstringToString(env, fName) + " " + jstringToString(env, lName) + ".n";
message += "You are " + decToHexa((int)age)+ " years old in hexadecimal. n";
message += "Your number is " + std::to_string(luckynum) + " n";
return env->NewStringUTF(message.c_str());

我的预期结果是,输入的名称具有个位数的结果,即 11、22、或 33。

Lambda 有一个封闭的范围。要访问父级的范围,您需要指定捕获默认值&=如下所示:

[&](char &c) {};
// or
[=](char &c) {};

从 https://en.cppreference.com/w/cpp/language/lambda:

&:通过引用隐式捕获使用的自动变量。
=:通过复制隐式捕获使用的自动变量。

您需要使用引用捕获,即[&]两种 lambda。您还需要声明int a = 0;.

请注意,语句[](int a=0){};不起作用,并且在其参数中声明的变量a在语句外部不可见。

最新更新