c++向量模板参数1无效

时间:2021-09-11 07:19:15

I wrote a File class in File.h. And I wrote Directory class in Directory.h which is include File& vector. Two header has same namespace.

我在File.h中编写了一个File类。我在目录中写了目录类。h包含文件和向量。两个头具有相同的名称空间。

Here is the code:

这是代码:

#include "File.h" 
#include <vector>

class Directory : public File
{
public:
    ...

private:
    std::vector<(File&)> files; 
};

When I try to compile it, it says:

当我试图编译它时,它说:

In file included from Directory.cpp:1:0:
Directory.h:29:30: error: template argument 1 is invalid
         std::vector<(File&)> files; 
                              ^
Directory.h:29:30: error: template argument 2 is invalid

1 个解决方案

#1


5  

To clear things up for you, std::vector requires its elements to be CopyAssignable, which references aren't.

为了让您清楚,std::vector要求它的元素是可CopyAssignable的,而引用不是CopyAssignable。

std::vector<File&> is a vector of references to File, note that std::vector<(File&)> is a syntax error.

向量 是文件的引用向量,注意std::vector<(File&)>是一个语法错误。 &>

You thought std::vector<File> & would work, but no. It's a reference to a vector of what? Objects. Polymorphism won't work there. And you'd need an actual std::vector<File> instance to refer to.

您认为std::vector &可以工作,但是不行。它是什么向量的一个引用?对象。多态性是行不通的。并且您需要一个实际的std::vector 实例来引用。

You need a vector of pointers, which can be copy-assigned.

你需要一个指针矢量,它可以被复制。

If you go with raw pointers, you'll need not to forget delete before you remove any element, or you'll leak memory (if an object was allocated on heap, of course). Smart pointers will do that for you:

如果使用原始指针,在删除任何元素之前,您不需要忘记删除,否则会泄漏内存(当然,如果对象被分配到堆上)。聪明的指针可以帮你做到:

std::vector<std::shared_ptr<File>> files;
// or
std::vector<std::unique_ptr<File>> files;

Reference: std::shared_ptr, std::unique_ptr.

参考:std::要查看,std::unique_ptr。

#1


5  

To clear things up for you, std::vector requires its elements to be CopyAssignable, which references aren't.

为了让您清楚,std::vector要求它的元素是可CopyAssignable的,而引用不是CopyAssignable。

std::vector<File&> is a vector of references to File, note that std::vector<(File&)> is a syntax error.

向量 是文件的引用向量,注意std::vector<(File&)>是一个语法错误。 &>

You thought std::vector<File> & would work, but no. It's a reference to a vector of what? Objects. Polymorphism won't work there. And you'd need an actual std::vector<File> instance to refer to.

您认为std::vector &可以工作,但是不行。它是什么向量的一个引用?对象。多态性是行不通的。并且您需要一个实际的std::vector 实例来引用。

You need a vector of pointers, which can be copy-assigned.

你需要一个指针矢量,它可以被复制。

If you go with raw pointers, you'll need not to forget delete before you remove any element, or you'll leak memory (if an object was allocated on heap, of course). Smart pointers will do that for you:

如果使用原始指针,在删除任何元素之前,您不需要忘记删除,否则会泄漏内存(当然,如果对象被分配到堆上)。聪明的指针可以帮你做到:

std::vector<std::shared_ptr<File>> files;
// or
std::vector<std::unique_ptr<File>> files;

Reference: std::shared_ptr, std::unique_ptr.

参考:std::要查看,std::unique_ptr。