How do I code and pass a (reference to a std::vector)?

前端 未结 2 1361
[愿得一人]
[愿得一人] 2021-01-23 19:22

I can\'t seem to get this right.

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

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


        
相关标签:
2条回答
  • 2021-01-23 19:51

    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.

    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) {}
    };
    
    0 讨论(0)
  • 2021-01-23 19:53

    You can initialize a reference only in an initialization list of a constructor. For instance,

    Tree::Tree( vector<type>& d ) : dict(d) 
    {
      ...
    }
    
    0 讨论(0)
提交回复
热议问题