我没有看到这一点,因为在operator []中,你正在返回一个 引用,无论如何,这将能够以多态方式使用。 /> 无论如何,无论你决定做什么,你都需要确保你不能构建一个不正确的缓冲区,在你的代码上调用以下内容将 是个问题: 缓冲区b< A>(新B [5],6) 它是'根本没必要引入那个问题,所以我已经改变了构造函数的(和简化)。 另外,你会注意到我'已经捕获了一个 std :: vector中的实际内容,因为我不理解指针和数组。 Ben Pope - 我不仅仅是一个数字。对很多人来说,我被称为字符串... I would probably make it like this: #include <vector> class A {};class B : public A {}; template<class Base, class Derived>class Buffer {public:Buffer(size_t size) : buffer_(size) {}Base& operator[](size_t i) { return buffer[i]; }private:std::vector<Derived> buffer_;}; int main() {Buffer<A, B> buf(5);} At the point of construction, you''re using the derived type, anyway. I don''t see the point, since in operator[], you''re returning areference, and that will be able to be used polymorphically, anyway. Anyway, whatever you decide to do, you need to make sure that you cannotconstruct an incorrect buffer, calling the following on your code wouldbe a problem: Buffer b<A>(new B[5], 6) It''s simply not necessary to introduce that problem, so I''ve changed(and simplified) the constructor. Also, you''ll notice I''ve captured the actual containing within astd::vector, since I don''t understand pointers and arrays. Ben Pope--I''m not just a number. To many, I''m known as a string... 这篇关于派生对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 15:03