简体   繁体   中英

Cpp Compile "error: unknown type name" when initializing object as member variable of other class

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:

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);

    LCache() {
        left->next = right;
        right->prev = left;
    }

    ~LCache() {
        delete left;
        delete right;
    }

    ...
};

That being said:

NULL is deprecated in modern C++, use nullptr instead.

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:

class Node{
public:
    int k;
    Node* prev = nullptr;
    Node* next = nullptr;
    
    Node (int key) : k(key) {}
};

class LCache {
private:
    std::unique_ptr<Node> left = std::make_unique<Node>(0);
    std::unique_ptr<Node> right = std::make_unique<Node>(0);

    LCache() {
        left->next = right;
        right->prev = left;
    }

    ...
};

/* alternatively:

class LCache {
private:
    Node left{0};
    Node right{0};

    LCache() {
        left.next = &right;
        right.prev = &left;
    }

    ...
};
*/

You're trying to do an assignment in the declaration of the class type. That makes no sense!

You probably wanted to write things such as "assign to left 's next field the value…" in some method of your code.

This far, this is plain invalid C++ – maybe go a little slower in your C++ intro. The step from "I write a C++ class and assign values to its fields" to "I build a graph" is non-negligible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM