【问题标题】:Error whilst creating a template operator创建模板运算符时出错
【发布时间】:2020-12-05 15:14:42
【问题描述】:

我用 C++ 编写了一个通用树,我的任务之一是创建一棵树。 为此,我需要在树之间创建一个运算符。 假设我可以从根目录中的信息中获取我知道的所有比较信息。 我创建了这些模板运算符重载。

template <class T>
class tree {
tree_node<T>* root;
tree_node<T> *largest;

public:
void roll(tree_node<T>* node);

tree();
~tree();
tree_node<T>* get_root();
void set_root(tree_node<T>*);
tree_node<T>* get_largest();
tree_node<T>* most_right(tree_node<T>* node);
void update_largest(tree_node<T>* node);
void update_largest_end(tree_node<T>* node);
tree_node<T>* find(T& data);
bool insert(T& data);
void del(tree_node<T>* node);
bool del(T& data);
void reverse_inorder(list<T>& list);
void partial_reverse_inorder(list<T>& list,int num);
friend bool operator<(const tree<T>& tree1,const tree<T>& tree2);
friend bool operator==(const tree<T>& tree1,const tree<T>& tree2);
};

template<class T>

bool operator<(const tree<T>& tree1,const tree<T>& tree2){

    return tree1.get_root()->data<tree2.get_root()->data; //assuming < operator

}

template <class T>

bool operator==(const tree<T>& tree1,const tree<T>& tree2){

    return tree1.get_root()->data==tree2.get_root()->data; //assuming == operator
}

但是当我尝试编译它时,我得到了这些错误消息:

E:\technion\mivnei\hw1\tree.h:75:68: 警告:友元声明 'bool operator

E:\technion\mivnei\hw1\tree.h:75:68: 注意:(如果这不是您想要的,请确保函数模板已经被声明并在此处的函数名称后添加 )

E:\technion\mivnei\hw1\tree.h:76:69: 警告:朋友声明 'bool operator==(const tree&, const tree&)' 声明了一个非模板函数 [-Wnon-template-friend ] 朋友布尔运算符==(常量树&树1,常量树&树2);

有谁知道出了什么问题或如何解决? (这不是关于代码正确性的问题,而只是关于重载运算符所需的语法)

【问题讨论】:

    标签: c++ templates operator-overloading friend


    【解决方案1】:

    你要么需要在类中定义非模板函数

    template <class T>
    class tree {
        // ...
        friend bool operator<(const tree<T>& tree1,const tree<T>& tree2){
            return tree1.get_root()->data<tree2.get_root()->data; //assuming < operator
        }
    };
    

    或声明友元函数模板:

    template <class T> class tree;
    
    template <class T> bool operator<(const tree<T>& tree1,const tree<T>& tree2);
    
    template <class T>
    class tree {
        // ...
        // Declare specialization friend
        friend bool operator< <T>(const tree<T>& tree1,const tree<T>& tree2);
    };
    
    template <class T> bool operator<(const tree<T>& tree1,const tree<T>& tree2)
    {
        return tree1.get_root()->data<tree2.get_root()->data; //assuming < operator
    }
    

    【讨论】:

    • 我认为它现在可以工作,但是在尝试使用运算符时我收到此错误消息:错误:将 'const tree' 作为 'this' 参数传递会丢弃限定符 [-fpermissive] return (( tree1.get_root())->数据)数据);其中“讲座”是我制作的另一门课
    • 你需要get_root的const版本:const tree_node&lt;T&gt;* get_root() const;
    • 非常感谢,我在这段代码面前坐了一个半小时,你在 5 分钟内修复了它,小伙子的道具
    猜你喜欢
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 2018-09-17
    • 2010-10-07
    相关资源
    最近更新 更多