Reputation: 2311
I've got a class where one of the private properties is an instance of the class. In Java (because I'm used to Java) this looks like:
class Node {
private Node Pi;
}
And now I'm writing this in C++, and when I try to do the same thing, I get a red underline (I'm using Visual C++ 2010 Express), "Incomplete type is not allowed".
class Node {
private:
Node Pi; //Incomplete type is not allowed
};
I've tried fixing this by changing it to Node Pi(void);
but then why I try to use another function that modifies this property I get "Expression must be a modifiable lvalue".
class Node {
private:
Node Pi(void);
public:
void setPi(Node n);
};
void Node::setPi(Node n) {
Pi = n; //Node Node::Pi() expression must be a modifiable lvalue
}
Normally in Java there's no problem with this, so my question is, how do I implement this? I'm not a beginner to C++, but I haven't written with it for a while.
class Node {
private Node Pi;
void setPi(Node n) {
this.Pi = n;
}
}
Upvotes: 0
Views: 142
Reputation: 88155
Java's syntax hides the fact that it uses pointers everywhere. In C++ you have to use pointer syntax explicitly in order to mimic Java:
// Java
class Node {
private Node Pi; // This is actually a pointer
}
// C++
class Node {
private:
Node *Pi; // So you use a pointer in C++ too
};
Upvotes: 1
Reputation: 500367
Turn Pi
into a reference or a pointer to Node
.
Node& Pi
) will result in nicer syntax, but can't be null, will have to be initialized at construction and cannot be changed to refer to a different object.Node* Pi
) will require less pretty syntax, but can be null and can be made to point to different objects at different times.For more details, see What are the differences between a pointer variable and a reference variable in C++?
Upvotes: 4
Reputation: 41
Change the following code :
class Node {
private:
Node Pi; //Incomplete type is not allowed
};
To:
class Node {
private:
Node* Pi;
};
Upvotes: 0
Reputation: 2728
Try this: (Send pointer to objects instead of class objects directly)
class Node {
private:
Node* Pi(void);
public:
void setPi(Node* n);
};
void Node::setPi(Node* n) {
Pi = n; //Node Node::Pi() expression must be a modifiable lvalue
}
Java 'auto-magically' converts those objects, with C++, you have to do it yourself.
Upvotes: 1