【问题标题】:Using structs as paramaters and accessing their elements in a template class使用 struct 作为参数并在模板类中访问它们的元素
【发布时间】:2011-10-23 11:20:09
【问题描述】:

我有一个模板类 btree,并在头文件的公共定义中定义了一个结构节点

struct Node {
    vector<Node> chi_;
    vector<T> val_;
    Node *par_;

    Node(size_t n, Node *parent) : par_(parent) {
        chi_.reserve(n+1);
        val_.reserve(n);
    }
    ~Node() {
        chi_.clear();
        val_.clear();
    }
};

作为我的 operator= / 复制构造函数的一部分,我想创建一个递归函数 'addAll'

template <typename T>
void btree<T>::addAll(struct Node* &one, struct Node* const& two) {

    for(unsigned int a = 0; a < two.val_.size(); a++)
        one.val_.push_back(two.val_.at(a));

    for(unsigned int a = 0; a < two.chi_.size(); a++) {
        Node *newNode = new Node(max, one);
        addAll(newNode, two.chi_.at(a));
        one.chi_.push_back(newNode);
    }
}

函数声明对我来说很奇怪——我尝试了一些简单的东西,比如 btree:addAll(节点 &one, const 节点 &two) 但这产生了很多难以理解的编译器错误,但我终于通过在上面声明它来接受所述函数的存在+有

void addAll(struct Node*&, struct Node* const&);

在我的头文件中。

我现在遇到的问题是在我的函数中访问节点的数据元素,我得到以下编译错误:

btree.tem:28:23: error: request for member 'val_' in 'two', which is of non-class type 'btree<long int>::Node* const'
btree.tem:29:3: error: request for member 'val_' in 'one', which is of non-class type 'btree<long int>::Node*'
btree.tem:29:3: error: request for member 'val_' in 'two', which is of non-class type 'btree<long int>::Node* const'
btree.tem:31:23: error: request for member 'chi_' in 'two', which is of non-class type 'btree<long int>::Node* const'
btree.tem:33:3: error: request for member 'chi_' in 'two', which is of non-class type 'btree<long int>::Node* const'
btree.tem:34:3: error: request for member 'chi_' in 'one', which is of non-class type 'btree<long int>::Node*'

不太确定我在这里是否正确地声明了事情,但这个特殊的问题真的让我很难过(接近一天半的不同方法来修补它,但无济于事)

【问题讨论】:

    标签: c++ templates struct


    【解决方案1】:

    onetwo是对指针的引用,所以需要使用-&gt;操作符来访问成员。

    one->val_.push_back(two->val_.at(a));
    

    此外,在 C++ 中,您在引用类型时不需要使用 struct 关键字。

    template <typename T>
    void btree<T>::addAll(Node* &one, Node* const& two)
    

    【讨论】:

      【解决方案2】:

      在取消引用指向类的指针时,您应该使用-&gt;

      例如:

      for(unsigned int a = 0; a < two->val_.size(); a++)
          one->val_.push_back(two->val_.at(a));
      

      【讨论】:

      • 我实际上只是尝试过,它导致了更痛苦的错误:
      • @Shaya 那你做错了,这是你提出的问题的正确答案。
      【解决方案3】:

      您已创建添加所有函数,一个是您的 btree 类的一部分,一个是类外的函数。您的 betree 类被定义为模板,但您的节点类是引用类型 T 的类。如果您的 b 树可以接受更多然后一个节点,那么添加所有应该引用一个 T 而不是一个节点,如果它只能利用节点类不应该是模板。

      【讨论】:

        猜你喜欢
        • 2021-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-05
        • 1970-01-01
        相关资源
        最近更新 更多