矢量未知大小

Vector unknown size

我有一个 class 播放器,其中包含一个实例变量:\

vector<Card> userCards;

为了避免任何编译错误,我转发声明了 class Card。但是现在,当我尝试构建解决方案时,我收到一条错误消息

Card *: Unknown size.

基本上我正在尝试创建一个包含非固定数量卡片的 Player,所以我尝试使用向量,但现在我无法让它工作。

Player.h

#include <iostream>
#include <vector>

using std::string;
using std::vector;

#ifndef PLAYER_H_
#define PLAYER_H_

class Card;
class Player {
private:
    vector<Card> userCards;
};
#endif

Card.h

#include <iostream>

using std::string;

#ifndef CARD_H_
#define CARD_H_

class Card {
private:
    string name;
    string type;

public:
    Card(const string& name, const string& type);   
};
#endif

我有一堆不相关的不同函数,所以我没有包括它们。

向量不必知道您要存储多少张卡片,但必须知道Card大小

所以不要转发声明,但是 #include Card.h。

std::vector 的类型模板参数不能是不完整的类型。它必须在实例化 std::vector<Card> 之前定义(完成)。为此,请将前向声明 class Card; 替换为 #include "Card.h" 指令。

您可以查看模板参数的进一步要求here

vector<Card> 需要查看 Card 的完整声明。有一些特定的函数需要实例化。

你可以做类似

vector<unique_ptr<Card>> userCards;

不过,它的行为与任何指针(引用)声明一样,并接受前向声明。

我假设您在 Player.h 文件中使用 #include "Card.h" 指令

但是,如果您没有被告知 std::vector<T> 要求它的参数是一个完整的类型,您不能传递一个前向声明的类型作为它的模板参数。

这里有另一个 question/answer 可以阐明您的问题:When can I use a forward declaration?