I have a string class in my c++ project. I have to use double linked list and make my own string class. In my string class I have to overload <
, >
and ==
operators. Actually I did this. But in my other class I have a listing function which compares my string classes. In this comparison I had "taking address of temporary" error.
Here is my string class:
#include "String.h"
String::String(int coming)
{
x=coming;
}
int String::getX()
{
return x;
}
String String::operator==(String *taken)
{
return String (x==taken->x);
}
and here is my listing method:
void myclass::list(String *taken)
{
otherclass *temp=head;
while(temp!=NULL)
{
if(&temp->get_string()==taken)//where i get error message.
cout<<temp<<endl;
temp=temp->get_nextnode();
}
}
The compiler is telling you precisely the problem: you cannot take the address of a temporary object. temp->get_string()
is a temporary object1, and you are trying to take its address.
I'm not really sure what your aim is here, so I can't suggest a fix. But I would strongly suggest that defining String::operator==
to take a pointer as the right-hand side will lead to confusion. And having it return another String
makes little sense either; normally one would expect ==
to evaluate to a boolean value.
get_string()
.