在 C++ 中,使用对象 vector 是个好主意吗?如果不是,这段 C++ 代码有什么问题?
#include <vector>
using namespace std;
class A {};
int main() {
vector<A*> v ( new A);
return 0;
}
来自 g++:
13: error: invalid conversion from
A*' to
unsigned int'
最佳答案
constructor for std::vector采用初始长度,而不是元素。
这意味着您通常会这样做:
vector<A*> v(1); // Initialize to length 1
v.push_back( new A() ); // Add your element...
您收到编译器错误是因为在您的系统上,size_type
被定义为 unsigned int
。它试图使用该构造函数,但失败了,因为您向它传递了一个指向 A 的指针。
关于C++,对象 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2411704/