gpt4 book ai didi

C++无法连接两个对象

转载 作者:行者123 更新时间:2023-11-28 02:55:25 24 4
gpt4 key购买 nike

我好久没接触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
}

最佳答案

你想通过引用传递:

void addElement(RedBlackTree<int> &RBT);
void peak(RedBlackTree<int> &RBT);

这不会创建对象的拷贝。

关于C++无法连接两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22129067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com