Hi, so the problem is that I was trying to make my
Tnode
class and one of the functions is supposed to find node with given
string
value and return pointer to that
Tnode
.
As I see it this operation is not changing the node itself so I tried to define it
const
but I couldn't. I had to write 2 different functions 1 for const version and one for non const
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
struct Tnode {
std::string word;
int count;
Tnode* left;
Tnode* right;
Tnode* parent;
~Tnode() { delete left; delete right; delete parent; }
void add_node(std::string, int);
//this alone didnt work
//Tnode* find(const std::string&) const;
const Tnode* find(const std::string&) const; //const version
Tnode* find(const std::string&); //non const version
};
|
Why I was unable to just define one function for both cases
Tnode* find(const std::string&) const;
As far as I remember if I have just this one last function, in case of const object I would return
const Tnode*
but if object is not const than just
Tnode*
I'm using Visual Studio 2015
EDIT :
Ok interesting news. I was not even able to write definition of
Tnode* find(const std::string& str)
I just want to create
find
version for both const and non const objects. What am I doing wrong?
If I write just one function like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
Tnode* Tnode::find(const std::string& str) const {
if (word == str) return this;
else if (str > word) {
//look in right node if it exists
if (right)
right->find(str);
else
return nullptr;
}
else if (str < word) {
//look in right node if it exists
if (left)
left->find(str);
else
return nullptr;
}
}
|
I cant return
this