我该如何编码和传递(对std :: vector的引用)? [英] How do I code and pass a (reference to a std::vector)?

查看:39
本文介绍了我该如何编码和传递(对std :: vector的引用)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法正确理解.

class Tree
{
    Node*   root;
    vector& dict;
} 

class Node
{
    vector& dict;
    char*   cargo;
    Node    left;
    Node    right;
}

我希望Tree的每个实例都有自己的字典,并希望将对字典的引用传递给节点构造函数,该构造函数将递归地将引用传递给每个子节点,以便每个Node可以输入一个指向本身在字典中.

I want each instance of Tree to have it's own dict, and I want it to pass a reference to the dict to the node constructor, which would recursively pass the reference to each child node so that each Node can enter a pointer to itself in the dict.

我在语法上遇到很多麻烦:

I'm having a lot of trouble with the syntax to:

  • 初始化向量
  • 将对向量的引用传递给Node构造函数
  • 在Node构造函数中接收引用

我知道这些东西很基础.我在自学c ++.

I know this stuff is pretty basic. I'm teaching myself c++.

谢谢

推荐答案

您还没有指定尝试的方法,但没有用,但是我怀疑您在构造函数中遇到了麻烦,因为引用不能分配给;您必须对其进行初始化.

You haven't specified what you've tried that isn't working, but I suspect you are having trouble in the constructors because a reference can't be assigned to; you have to initialize it.

此外,当您使用 std :: vector 时,必须使用模板参数作为元素类型.因此,您不能只使用 vector& ,还需要 vector< Something>& ,其中 Something 是元素类型是什么.

Also, when you use std::vector, you have to use a template parameter for the element type. So you can't just use vector&, you need vector<Something>&, where Something is whatever the element type is.

所以,您可能想要这样的东西:

So, you probably want something like this:

class Tree
{
private:
    Node* root;
    std::vector<Something>& dict;

public:
    Tree(Node* aRoot, std::vector<Something>& aDict): root(aRoot), dict(aDict) {}
};

class Node
{
private:
    std::vector<Something>& dict;
    char*cargo;
    Node left;
    Node right;

    Node(std::vector<Something>& aDict, char* aCargo): dict(aDict), cargo(aCargo) {}
};

这篇关于我该如何编码和传递(对std :: vector的引用)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆