Reputation: 1678
I have to create an own string class for a university project, my code so far looks like(I only show the relevant parts):
class SuchString
{
char* str;
size_t siz;
public:
SuchString(char* a);
~SuchString();
SuchString(SuchString& a);
SuchString operator+(const SuchString& a) const;
...
...
};
As you can see I have a constructor for char*
types, implemented as:
SuchString::SuchString(char* a)
{
siz = strlen(a);
str = new char[siz];
strcpy(str, a);
}
The problem is with my operator+
function:
SuchString SuchString::operator+(const SuchString &a) const
{
return SuchString(strcat(str, a.str));
}
I get the following error message:
No matching constructor for initialization of 'SuchString'
As far my understanding goes, the strcat
function should return with a char*
, and I have a constructor for that type.
I get the same error message for the following:
SuchString SuchString::operator+(const SuchString &a) const
{
char* lel = strcat(str, a.str);
return SuchString(lel);
}
And again, the same thing happens. I expected that the code SuchString(lel)
would create a temporary variable, so the function can return with it, just as in the previous example.
Any help is appreciated.
ps: I know it's absolute nonsense to create a string class like this, but this is some small project for university.
Upvotes: 1
Views: 357
Reputation: 258678
SuchString(SuchString& a);
takes a non-const
reference as a parameter, so passing it temporaries is not doable. What you probably want is
SuchString(const SuchString& a);
because when you return by value, a copy is made - i.e.:
return SuchString(lel);
will create a temporary SuchString
which is then copied and returned. In theory, that is, because in practice the copy is most likely optimized out.
Upvotes: 3