4

尝试编译此代码时:

#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
...

错误在哪里?

4

3 回答 3

9

问题是您正在尝试创建参考向量。要存储在向量中的对象类型必须是可分配的,而引用则不是这样。引用只能在声明时初始化,以后不能更改。

你最可能想要的是

Test t(31415);
std::vector<Test> vet;
vet.push_back(t);

它创建一个副本t,然后存储在向量中。

您实际上可以在编译器错误消息中看到问题,尽管它们非常神秘。编译器无法为 a 生成代码*allocator<Test&>,该代码负责分配要存储在向量中的对象的内存 - 无法为引用分配内存。

于 2012-06-15T01:06:01.590 回答
1

如果复制不符合要求,您可以使用新的 c++11移动语义或使用指针向量Test

于 2012-06-15T01:14:05.863 回答
1

正如其他人所说,您可以创建一个指针向量:

vector<Object*> vet;
...
while (blabla) {
    Object* I = SF.CurObject++;
    vet.push_back(I);
}

如果您坚持,您仍然可以使用参考:

Object& Iref = *I;
于 2012-06-15T01:38:58.377 回答