I'm new to C++. I am initializing a class object Node in another class LCache. When I try to compile my code, I get the following error:
Line 22: Char 5: error: unknown type name 'left'
left -> next = right;
^
Below is the code I have written:
class Node{
public:
int k;
Node* prev;
Node* next;
Node (int key){
k=key;
prev=NULL;
next=NULL;
}
};
class LCache {
private:
Node* left = new Node(0);
Node* right = new Node(0);
left -> next = right;
right -> prev = left;
...
When I move left -> next = right; and right -> prev = left; inside a method in class LCache, the error goes away. Can you explain the reason here?
You can't perform non-declaration statements inside of a class declaration, like you are trying to do. You need to perform them inside of a class member function instead, or in this case inside of the class constructor (like you did with
Node), eg:That being said:
NULLis deprecated in modern C++, usenullptrinstead.And you should use smart pointers whenever you have owned pointers that need freeing when they are done being used. Or better, just don't use objects dynamically when you don't actually need to.
Try something more like this instead: