Re: Returning a Pointer to a Struct
Spiffy <sylvesterc@gmail.com> writes:
When I created a function to return a pointer to a Struct, GCC returns
"error: cannot convert =E2=80=98linklist::node*=E2=80=99 to =E2=80=98node=
linklist::*=E2=80=99 in
return" about the return line. I have tried a bunch of things to no
avail. This is a three part question.
1) What it would take to get the code below to compile?
2) How come within this function, I needed to specify class name
when referring to the Struct, while other public or private function
doesn't have to?
3) Ideally, I would keep the Struct private, but that caused more
compiler error. Is this possible?
Thanks!
class linklist {
public:
struct node {
int data;
node *link;
};
linklist();
~linklist();
void append( int num );
private:
struct node *p;
struct node *addnode( int num );
};
struct node linklist::*addnode ( int num ) {
This is parsed as:
((struct node) linklist::*) addnode ( int num )
The of the result is ((struct node) linklist::*) which means a
pointer to a member of the class linklist, which points to a struct
node.
To return such a type, you would have to declare a member to the class
linklist:
*/
class linklist{
private:
struct node myNode;
/*
and return it:
*/
struct node linklist::*addnode ( int num ) {
return(*myNode);
}
/*
which of course is not what you want, so one wonders why you write
such as return type...
linklist::node *t;
return (linklist::node*)t;
You don't need to qualify the names in the same class as the method in
its body. Of course, this would be true only if it was a method of
that class, and not a normal function. For this, you would have to write:
struct node* linklist::addnode ( int num ) {
node* t=new node();
return(t);
}
--
__Pascal Bourguignon__