I am getting an error when trying to pass a variable as a reference parameter into a function. The problem is the variable is a private member variable. Therefore, if I use a get function ie getItem() which is of type int, it will pass a const int into the function and the error is thrown.
If the member variable wasn't private I could just throw that at a parameter, but I can't. Can someone please explain how this works? What I'm doing wrong? Thanks.
gnu g++ output:
heap.cxx:123: error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’
Code:
template <class Process, class Param, class Item, class Key>
bool process_node(heapnode<Item, Key> *root, Key k, Process f, Param p);
Code:
template <class Process, class Param, class Item, class Key>
bool process_node(heapnode<Item, Key> *root, Key k, Process f, Param p)
{
if(!check_node(root, k)) //if node doesn't exist, return false
return false;
heapnode<Item, Key>* target = search(root, k); //create pointer to target node
if( f(target->getItem(), p) ) //apply Process f with Param p to the given target ***** This is where im having trouble??
return true;
else
return false;
}
Code:
#include <iostream>
#include <cstdlib>
#include <stack>
#include "heap.h"
using namespace std;
using namespace assignment5;
void print_item(int n)
{
cout << n << endl;
}
void multiply(int& n, int b)
{
n = n * b;
}
int main( )
{
heapnode<int, int> *mydb = NULL;
insert_node(mydb, 0, 100);
insert_node(mydb, 3, 90);
insert_node(mydb, 6, 80);
insert_node(mydb, 2, 70);
insert_node(mydb, 1, 5000);
insert_node(mydb, 5, 1000);
insert_node(mydb, 11, 101);
insert_node(mydb, 4, 201);
cout << endl;
if (process_node(mydb, 2, multiply, 5)) cout << "process_node done" << endl;
else cout << "process_node not done" << endl;
postorder_processing(mydb, print_item);
cout << endl;
if (process_node(mydb, 1, multiply, 5)) cout << "process_node done" << endl;
else cout << "process_node not done" << endl;
postorder_processing(mydb, print_item);
cout << endl;
if (process_node(mydb, 10, multiply, 5)) cout << "process_node done" << endl;
else cout << "process_node not done" << endl;
postorder_processing(mydb, print_item);
}