C++;无法连接两个对象 当我遇到这个问题时,我已经很久没有接触C++了,试图制作一个红黑树模板。我想添加一个元素,然后就可以了。但是当我切换函数时,我无法拥有相同的RBT变量。它随着成为一个全新的变量而变化。我不知道这为什么不起作用 #include <iostream> #include <string> #include "redblacktree.h" using namespace std; int menu(); void addElement(RedBlackTree<int> RBT); void peak(RedBlackTree<int> RBT); int main() { int option=-1; RedBlackTree<int> RBT; while(option != 99) { option=menu(); switch(option) { case 1: addElement(RBT); break; case 3: peak(RBT); break; } } return 0; } int menu() { int option; cout<<"1. Add element"<<endl; cout<<"3. Peek"<<endl; cin>>option; cin.ignore(); return option; } void addElement(RedBlackTree<int> RBT) { int value; cout<<"Enter element: "<<endl; cin>>value; cin.ignore(); RBT.insert(value); //cout<<RBT.printRoot()<<endl; //works } void peak(RedBlackTree<int> RBT) { cout<<RBT.printRoot()<<endl; //does not work } #包括 #包括 #包括“redblacktree.h” 使用名称空间std; int菜单(); 无效附加元素(红黑树RBT); 空隙峰值(红黑树RBT); int main() { int选项=-1; 红黑树RBT; while(选项!=99) { 选项=菜单(); 开关(选件) { 案例1: 附加元素(RBT); 打破 案例3: 峰值(RBT); 打破 } } 返回0; } int菜单() { int选项; cout

C++;无法连接两个对象 当我遇到这个问题时,我已经很久没有接触C++了,试图制作一个红黑树模板。我想添加一个元素,然后就可以了。但是当我切换函数时,我无法拥有相同的RBT变量。它随着成为一个全新的变量而变化。我不知道这为什么不起作用 #include <iostream> #include <string> #include "redblacktree.h" using namespace std; int menu(); void addElement(RedBlackTree<int> RBT); void peak(RedBlackTree<int> RBT); int main() { int option=-1; RedBlackTree<int> RBT; while(option != 99) { option=menu(); switch(option) { case 1: addElement(RBT); break; case 3: peak(RBT); break; } } return 0; } int menu() { int option; cout<<"1. Add element"<<endl; cout<<"3. Peek"<<endl; cin>>option; cin.ignore(); return option; } void addElement(RedBlackTree<int> RBT) { int value; cout<<"Enter element: "<<endl; cin>>value; cin.ignore(); RBT.insert(value); //cout<<RBT.printRoot()<<endl; //works } void peak(RedBlackTree<int> RBT) { cout<<RBT.printRoot()<<endl; //does not work } #包括 #包括 #包括“redblacktree.h” 使用名称空间std; int菜单(); 无效附加元素(红黑树RBT); 空隙峰值(红黑树RBT); int main() { int选项=-1; 红黑树RBT; while(选项!=99) { 选项=菜单(); 开关(选件) { 案例1: 附加元素(RBT); 打破 案例3: 峰值(RBT); 打破 } } 返回0; } int菜单() { int选项; cout,c++,C++,当前您将RedBlackTree RBT传递到addElement()和peak()中。根据C++的传递值性质,实例在传递到函数之前会被复制。因此,函数在临时副本上工作 要使函数在传入的实例上工作,应通过引用传递参数。在这种情况下,将RedBlackTree&传递到addElement()和peak() 另外,由于您说您的peak()不起作用,您应该检查您的复制构造函数是否正确。您必须通过引用传递,因为您正在通过添加新元素修改对象 在您的解决方案中,在addElement的末尾,RBT被简单地销

当前您将
RedBlackTree RBT
传递到
addElement()
peak()
中。根据C++的传递值性质,实例在传递到函数之前会被复制。因此,函数在临时副本上工作

要使函数在传入的实例上工作,应通过引用传递参数。在这种情况下,将
RedBlackTree&
传递到
addElement()
peak()


另外,由于您说您的
peak()
不起作用,您应该检查您的复制构造函数是否正确。

您必须通过引用传递,因为您正在通过添加新元素修改对象


在您的解决方案中,在addElement的末尾,RBT被简单地销毁,因为它的行为类似于局部变量,超出了范围。

您希望通过引用传递:

void addElement(RedBlackTree<int> &RBT);
void peak(RedBlackTree<int> &RBT);
void addElement(RedBlackTree&RBT);
空洞峰(红黑树和RBT);
这不会创建对象的副本