简体   繁体   English

如何在另一个类中定义模板类变量?

[英]How to define a template class variable inside of another class?

I defined a template class first, then defined another class Node_3, and in that class I defined a variable that its type is class first called Tree_2. 我先定义了一个模板类,然后定义了另一个类Node_3,然后在该类中定义了一个变量,其类型首先是称为Tree_2的类。 Now this worked fine, but when I try to write a function getTree_2 which is supposed to return the Tree_2 class I get an error, I can't understand why... The error I get: 现在可以正常工作,但是当我尝试编写应该返回Tree_2类的函数getTree_2时,出现错误,我不明白为什么...得到的错误:

  • Invalid arguments ' Candidates are: first < second::Node_2,second::Cmp_node2> * 无效的参数'候选者是:first <second :: Node_2,second :: Cmp_node2> *
    Tree_2(second::Cmp_node2) ' Tree_2(second :: Cmp_node2)'

Something like this: 像这样:

template <class element, class compare_fuc>
class first {
   int x;
   compare_fuc cmpFunc;
   // more things here
   public:
         first(compare_fuc cmp): x(0),cmpFunc(cmp) {};
         ~first() {};

         // and more things here
   };

Now I defined another class that is supposed to define a variable from class first type: 现在,我定义了另一个类,该类应该从类第一个类型定义一个变量:

class second{

private:

class Node_2{
    int y1;
    int y2;
    public:

    explicit Node_2(int y1,int y2) : y1(y1),y2(y2){};

    ~Node_2() {};
};

class Node_3{
private:
//Cmp_node2 is a class i defined that compares nodes 2
first<Node_2,Cmp_node2>* Tree_2(Cmp_node2);
puclic:
    first<Node_2,Cmp_node2>* getTree_2()
    {
        return Tree_2;  /// here i get the error
    }
};
};

Well, first, you haven't provided a definition of Cmp_node2 ; 好吧,首先,您没有提供Cmp_node2的定义; and you have some typos. 而且你有错别字。 But when we fix your code , we see that the problem is that you've mis-defined Type2 , that's all: 但是,当我们修复您的代码时 ,我们发现问题在于您误定义了Type2 ,仅此Type2

<source>: In member function 'first<second::Node_2, second::Cmp_node2>* 
second::Node_3::getTree_2()':

<source>:40:20: error: cannot convert 'second::Node_3::Tree_2' 
from type 'first<second::Node_2, second::Cmp_node2>*(second::Node_3::)(second::Cmp_node2)' 
to type 'first<second::Node_2, second::Cmp_node2>*'

Why do you get this? 你为什么得到这个? Well, look at the definition: 好吧,看一下定义:

first<Node_2,Cmp_node2>* Tree_2(Cmp_node2);

You thought you were defining a member variable of type first<whatever>* , but actually, you defined a member function which takes a Cmp_node2 and returns a first<whatever>* ! 您以为您正在定义类型为first<whatever>*的成员变量 ,但实际上,您定义了一个成员函数 ,该成员函数使用Cmp_node2并返回first<whatever>*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM