gpt4 book ai didi

c++ - 创建局部结构的 std::vector 时出错

转载 作者:可可西里 更新时间:2023-11-01 16:29:12 25 4
gpt4 key购买 nike

#include <vector>
int main() {
struct st { int a; };
std::vector<st> v;
for (std::vector<st>::size_type i = 0; i < v.size(); i++) {
v.operator[](i).a = i + 1; // v[i].a = i+1;
}
}

以上代码在使用 GNU g++ 编译器编译时会出现以下错误。

test.cpp: In function ‘int main()’:
test.cpp:6:19: error: template argument for ‘template<class _Alloc> class std::allocator’ uses local type ‘main()::st’
test.cpp:6:19: error: trying to instantiate ‘template<class _Alloc> class std::allocator’
test.cpp:6:19: error: template argument 2 is invalid
test.cpp:6:22: error: invalid type in declaration before ‘;’ token
test.cpp:7:24: error: template argument for ‘template<class _Alloc> class std::allocator’ uses local type ‘main()::st’
test.cpp:7:24: error: trying to instantiate ‘template<class _Alloc> class std::allocator’
test.cpp:7:24: error: template argument 2 is invalid
test.cpp:7:37: error: expected initializer before ‘i’
test.cpp:7:44: error: ‘i’ was not declared in this scope
test.cpp:7:50: error: request for member ‘size’ in ‘v’, which is of non-class type ‘int’
test.cpp:8:20: error: request for member ‘operator[]’ in ‘v’, which is of non-class type ‘int’

为什么我无法创建结构 vector ?

最佳答案

在 C++11 之前,您无法使用本地类实例化模板。您有两个选择:

1) 将 st 定义放在 main 之外

#include <vector>

struct st { int a; };

int main()
{
std::vector<st> v;
}

2) 用c++11编译器编译

关于c++ - 创建局部结构的 std::vector 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21931830/

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