C ++ tree output error
for my class of data structures, we create a data structure that we can use to easily store and organize data. I have a problem with the output function of my tree. The error message I am getting:
AccountDB.cpp: In member function โvoid AccountDB::output(std::ostream&) constโ:
AccountDB.cpp:23:21: error: passing โconst AccountDBโ as โthisโ argument of โvoid
AccountDB::output(std::ostream&, const AccountDB::Elem*)โ discards qualifiers [-fpermissive]
I look around and my output code looks very similar to what other people have done. I have no idea and I am at a loss as to what the error is trying to say.
Thank you for your help.
Title:
#ifndef ACCOUNTDB_H
#define ACCOUNTDB_H
#include <iostream>
using namespace std;
#include "AccountRecord.h"
class AccountDB {
public:
AccountDB();
~AccountDB();
void insert( const AccountRecord &v );
AccountRecord * get( const AccountRecord &v );
void output( ostream &s ) const;
private:
struct Elem {
AccountRecord info;
Elem *left;
Elem *right;
};
Elem *root;
void insert( const AccountRecord &v, Elem *&e );
AccountRecord * get( const AccountRecord &v, Elem *&e );
void output( ostream &s, const Elem *e );
};
ostream &operator << ( ostream &s, const AccountDB &v );
#endif
Source
#include "AccountDB.h"
//default constructor
AccountDB::AccountDB() {
root = 0;
}
//destructor
AccountDB::~AccountDB() {
}
//public
void AccountDB::insert( const AccountRecord &v ) {
return insert( v, root );
}
AccountRecord * AccountDB::get( const AccountRecord &v ) {
return get( v, root );
}
void AccountDB::output( ostream &s ) const {
output( s, root );
}
//private
void AccountDB::insert( const AccountRecord &v, Elem *&e ) {
if( e == NULL ) {
e = new Elem();
e->info = v;
}
else if( v < e->info )
insert( v, e->left );
else if( v > e->info )
insert( v, e->right );
}
AccountRecord * AccountDB::get( const AccountRecord &v, Elem *&e ){
if( e->info == v )
return &(e->info);
else if( v < e->info && e->left != NULL )
get( v, e->left );
else if( v > e->info && e->right != NULL )
get( v, e-> right );
else
return NULL;
}
void AccountDB::output( ostream &s, const Elem *e ) {
if( e != NULL ) {
output( s, e->left );
s << e->info << endl;
output( s, e->right );
}
}
ostream &operator << ( ostream &s, const AccountDB &v ) {
v.output( s );
return s;
}
source to share
Your function is output
to be announced const
, so when you call
output( s, root );
the compiler tells you that you are calling a non-const function from within the function const
.
There are several ways to handle this - you have to make it output
const the other is to make it output
static (if possible).
source to share
The error is that
void AccountDB::output( ostream &s, const Elem *e )
is not declared as const
, but you call it from a method const
.
Change the declaration (and definition) to:
void output( ostream &s, const Elem *e ) const;
You can do this since you don't change any members inside the function.
source to share