【发布时间】:2018-11-08 00:37:12
【问题描述】:
我有可以正确编译和工作的 C 代码,我想在 C++ 中使用类似的代码:
static const char* aTable[12] = {
[4]="seems",
[6]=" it ",
[8]="works",};
int main(){
printf("%s%s%s", aTable[4],aTable[6],aTable[8]);
return 0;
}
现在,如果我将它放在 .c 文件中并使用 gcc 进行编译,它就可以工作。但是,如果我把它放在一个.cpp 文件中并用g++ 编译它,我会得到以下错误:
test_cpp.cpp:5:3: error: expected identifier before numeric constant
test_cpp.cpp:5:4: error: type '<lambda>' with no linkage used to declare function 'void<lambda>::operator()() const' with linkage [-fpermissive]
test_cpp.cpp: In lambda function: test_cpp.cpp:5:5: error: expected '{' before '=' token
test_cpp.cpp: At global scope: test_cpp.cpp:5:5: warning: lambda expressions only available with
-std=c++0x or -std=gnu++0x [enabled by default]
test_cpp.cpp:5:6: error: no match for 'operator=' in '{} = "seems"' test_cpp.cpp:5:6: note: candidate is: test_cpp.cpp:5:4: note: <lambda()>&<lambda()>::operator=(const<lambda()>&)
test_cpp.cpp:5:4: note: no known conversion for argument 1 from 'const char [6]' to 'const<lambda()>&'
test_cpp.cpp:6:3: error: expected identifier before numeric constant
test_cpp.cpp:6:4: error: type '<lambda>' with no linkage used to declare function 'void<lambda>::operator()() const' with linkage [-fpermissive]
有没有办法表示我没有声明 lambda 函数,只是想填一张表?
我想保留以下部分:
[4]="seems",
[6]=" it ",
[8]="works",
因为它来自自动生成的文件...
【问题讨论】:
-
还记得 C 和 C++ 是不同的语言吗?即使对于历史版本的编译器也存在一些不兼容问题,那么对于最近编译器的现代扩展来说,问题是最糟糕的。
-
或者用现代C编译器编译那个文件并链接。
-
很少有 c 和 c++ 标签都在主题上。最重要的是,这很好地表明,与常见的误解相比,c++ 不是 c 的超集。多么好的问题:)
-
看起来这将在 C++20 中被允许......
-
@aschepler 我认为 C++20 提案仅适用于
.name = value,而不是[index] = value。