重载运算符 + 用于在二叉树中插入节点
Overloading operator + for inserting a node in a BinaryTree
这些是我的 类 二叉树:
class Node
{
friend class BinaryTree;
int value;
Node *left, *right;
};
class BinaryTree
{
private :
Node *first ;
public :
void insert_node(int x);
void delete_node(int x);
void in_order_traversal();
void print_leafs (Node *first);
void print_leafs2 ();
int get_height();
BinaryTree();
~BinaryTree();
// operator oveloading
};
我想重载 + 运算符以便我可以向树中插入一个新元素,序列应该是这样的:
int x;
BinaryTree *bt;
x + bt; // or bt + x;
我已经有了一个向树中插入节点的方法,我所要做的就是在重载运算符 + 代码中调用该方法。这就是我尝试这样做的方式:
//inline declaration
friend BinaryTree& operator + ( BinaryTree& bt, const int x)
{
bt.insert_node(x);
return bt;
}
我不知道为什么,但是当我调试这段代码时,行
bt + x;
被编译器忽略。
任何帮助将不胜感激:)
由于 x
被声明为 int
并且 bt
被声明为指针,使用 x + bt;
或 bt + x;
计算为指针和值被丢弃。
为了调用函数 friend BinaryTree& operator + ( BinaryTree& bt, const int x)
,运算符的 LHS 必须是类型 BinaryTree
的对象,而不是指向 BinaryTree
.
的指针
您需要使用:
*bt + x;
这只是句法部分。从语义上讲,那个运算符重载函数好像不太对。
当你使用
int a = 10;
a + 20;
a
的值未更改。最后一行简单地评估为 30
并且该值被丢弃。
如果你使用
int b = a + 20;
b
被分配了 30
的值,但 a
保持不变。您可能希望为运算符重载函数创建类似的语义。
BinaryTree bt1; // Create an empty tree.
BinaryTree bt2 = bt1 + 1; // bt2 contains everything in bt1 + 1.
在那种情况下,将函数更改为:
friend BinaryTree operator + ( BinaryTree const& bt, int x)
// | | ^^^ No need for const
// | ^^^^^^^^ Change it to const&
// ^^^ Change the return type to be an object, not a reference.
{
BinaryTree ret(bt); // Provide a proper copy constructor
ret.insert_node(x);
return ret;
}
这些是我的 类 二叉树:
class Node
{
friend class BinaryTree;
int value;
Node *left, *right;
};
class BinaryTree
{
private :
Node *first ;
public :
void insert_node(int x);
void delete_node(int x);
void in_order_traversal();
void print_leafs (Node *first);
void print_leafs2 ();
int get_height();
BinaryTree();
~BinaryTree();
// operator oveloading
};
我想重载 + 运算符以便我可以向树中插入一个新元素,序列应该是这样的:
int x;
BinaryTree *bt;
x + bt; // or bt + x;
我已经有了一个向树中插入节点的方法,我所要做的就是在重载运算符 + 代码中调用该方法。这就是我尝试这样做的方式:
//inline declaration
friend BinaryTree& operator + ( BinaryTree& bt, const int x)
{
bt.insert_node(x);
return bt;
}
我不知道为什么,但是当我调试这段代码时,行
bt + x;
被编译器忽略。
任何帮助将不胜感激:)
由于 x
被声明为 int
并且 bt
被声明为指针,使用 x + bt;
或 bt + x;
计算为指针和值被丢弃。
为了调用函数 friend BinaryTree& operator + ( BinaryTree& bt, const int x)
,运算符的 LHS 必须是类型 BinaryTree
的对象,而不是指向 BinaryTree
.
您需要使用:
*bt + x;
这只是句法部分。从语义上讲,那个运算符重载函数好像不太对。
当你使用
int a = 10;
a + 20;
a
的值未更改。最后一行简单地评估为 30
并且该值被丢弃。
如果你使用
int b = a + 20;
b
被分配了 30
的值,但 a
保持不变。您可能希望为运算符重载函数创建类似的语义。
BinaryTree bt1; // Create an empty tree.
BinaryTree bt2 = bt1 + 1; // bt2 contains everything in bt1 + 1.
在那种情况下,将函数更改为:
friend BinaryTree operator + ( BinaryTree const& bt, int x)
// | | ^^^ No need for const
// | ^^^^^^^^ Change it to const&
// ^^^ Change the return type to be an object, not a reference.
{
BinaryTree ret(bt); // Provide a proper copy constructor
ret.insert_node(x);
return ret;
}