尝试编译这段代码时:
#include <iostream>
#include <vector>
using namespace std;
class Test {
int a;
public:
Test(int pa) : a(pa) { }
void print() {
std::cout << a << std::endl;
}
};
int main() {
Test t(31415);
t.print();
vector<Test &> vet;
vet.push_back(&t);
return 0;
}
gcc 4.4.5-8 报告各种错误,开始于:
In file included from /usr/include/c++/4.4/i486-linux-gnu/bits/c++allocator.h:34,
from /usr/include/c++/4.4/bits/allocator.h:48,
from /usr/include/c++/4.4/string:43,
from /usr/include/c++/4.4/bits/locale_classes.h:42,
from /usr/include/c++/4.4/bits/ios_base.h:43,
from /usr/include/c++/4.4/ios:43,
from /usr/include/c++/4.4/ostream:40,
from /usr/include/c++/4.4/iostream:40,
from references.cpp:1:
/usr/include/c++/4.4/ext/new_allocator.h: In instantiation of ‘__gnu_cxx::new_allocator<Test&>’:
/usr/include/c++/4.4/bits/allocator.h:87: instantiated from ‘std::allocator<Test&>’
/usr/include/c++/4.4/bits/stl_vector.h:71: instantiated from ‘std::_Vector_base<Test&, std::allocator<Test&> >’
/usr/include/c++/4.4/bits/stl_vector.h:171: instantiated from ‘std::vector<Test&, std::allocator<Test&> >’
references.cpp:22: instantiated from here
...
哪里出错了?
最佳答案
问题是您正在尝试创建一个引用 vector 。要存储在 vector 中的对象的类型必须是可分配的,而引用则不是这样。引用只能在声明时初始化,以后不能更改。
你最可能想要的是
Test t(31415);
std::vector<Test> vet;
vet.push_back(t);
创建 t
的拷贝然后将其存储在 vector 中。
您实际上可以在编译器错误消息中看到问题,尽管它们非常隐晦。编译器无法为 *allocator<Test&>
生成代码,它负责存储在 vector 中的对象的内存分配——没有办法为引用分配内存。
关于c++ - 用户定义类型的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11043364/