Binary trees in C ++ using references

I want to implement a binary tree using links instead of using pointers (which, as a rule, you will find in every book and on every website on the Internet). I tried the following code:

class tree_node {
private:
    tree_node& left;
    tree_node& right;
    data_type data;
public:
    void set_left(tree_node&);
    // ... other functions here
};

void tree_node::set_left(tree_node& new_left) {
    this.left = new_left;
}

I get the following error: error C2582: function 'operator =' is not available in 'tree_node'.

I know that I can easily implement it with pointers, but I would like to keep my solution elegant and without pointers. Can you tell me where I am going wrong?

+3
source share
5 answers

, 1; , .

. ( , , , !)

(1) , , , !

+4

. , , ... .. ( node , ).

, .

+2

- . , , lhs .

int i = 3;
int j = 4;
int &ref = i;
ref = j;
std::cout << i << "\n"; // prints 4: i itself has been modified, 
                        // because semantically ref *is* i

, ref = j , i = j, , *ptr = j, int *ptr = &i;. , " j ref ".

ref i. - int, "".

, , .

, this.left = new_left, , " new_left this.left". () , , this.left (), , , , this.left , .

(b) , () .

+2

++ , . , .

+1

My recommendation is to use the boost shared_ptr class instead . This frees you from worrying about managing pointer deallocation. You may also be interested in Boost graph library .

+1
source

Source: https://habr.com/ru/post/1767611/


All Articles