在类中定义模板类变量后,返回该变量时出现参数错误的咨询
问题分析与解决方案
嘿,我一下子就揪出你代码里的问题啦!
核心错误原因
你在Node_3里对Tree_2的定义完全写错了——它被编译器当成了成员函数声明,而不是你想要的成员变量!
看你这段代码:
first<Node_2,Cmp_node2>* Tree_2(Cmp_node2);
在C++语法里,这行代码的含义是:声明一个名为Tree_2的成员函数,它需要接收一个Cmp_node2类型的参数,返回first<Node_2,Cmp_node2>*类型的指针。
所以当你在getTree_2里直接写return Tree_2;时,编译器以为你要调用这个Tree_2函数,但你没传它要求的参数,这就触发了你看到的参数不匹配错误。
另外你的代码里还有个低级拼写错误:puclic应该改成public,不然编译器也会直接报错。
修正后的代码示例
下面是调整后的正确代码,我帮你修正了变量声明和拼写问题,还补充了Node_3的构造函数来初始化Tree_2:
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 }; class second{ private: class Node_2{ int y1; int y2; public: explicit Node_2(int y1,int y2) : y1(y1),y2(y2){}; ~Node_2() {}; }; // 假设你已经定义了Cmp_node2类,这里补个示例实现 class Cmp_node2 { public: bool operator()(const Node_2& a, const Node_2& b) { // 这里填写你的Node_2比较逻辑 return a.y1 < b.y1; } }; class Node_3{ private: // 修正:把Tree_2声明为成员变量,而非函数 first<Node_2,Cmp_node2>* Tree_2; public: // 构造函数:初始化Tree_2(需要传入Cmp_node2实例) Node_3() { Tree_2 = new first<Node_2,Cmp_node2>(Cmp_node2()); } // 析构函数:记得释放指针内存 ~Node_3() { delete Tree_2; } first<Node_2,Cmp_node2>* getTree_2() { return Tree_2; // 现在这行完全没问题啦 } }; };
额外小建议
如果不是必须用指针,建议直接用对象而非指针,这样能避免手动管理内存的麻烦。比如把Tree_2声明为first<Node_2,Cmp_node2> Tree_2;,然后在构造函数里初始化:Tree_2(Cmp_node2())。
内容的提问来源于stack exchange,提问作者jena90
相关产品推荐
相关产品推荐

