I want to ask a question about friends of a class in C++.
I am a beginner in C++ and learning about overloading operators as global functions.
I wrote the following part of a class declaration in the Mystrings.h
file and the corresponding function in the Mystrings.cpp
file.
for Mystrings.h
:
class Mystring
{
friend bool operator==(const Mystring &lhs, const Mystring &rhs);
friend Mystring operator-(const Mystring &obj);
friend Mystring operator+(const Mystring &lhs, const Mystring &rhs);
private:
char *str; // pointer to a char[] that holds a c-style string
and for Mystrings.cpp
:
Mystring operator-(Mystring &obj) {
char *buff = new char[std::strlen(obj.str)+1];
std::strcpy(buff, obj.str);
for (size_t i = 0; i < std::strlen(buff); i++)
buff[i] = std::tolower(buff[i]);
Mystring temp {buff};
delete [] buff;
return temp;
}
// concatenation
Mystring operator+(const Mystring &lhs, const Mystring &rhs) {
char *buff = new char [std::strlen(lhs.str) + std::strlen(rhs.str) + 1];
std::strcpy(buff, lhs.str);
std::strcat(buff, rhs.str);
Mystring temp {buff};
delete [] buff;
return temp;
}
For my main CPP file I was trying to make the following work:
Mystring three_stooges = moe + " " + larry + " " + "Curly";
three_stooges.display(); // Moe Larry Curly
However, the compiler returns an error:
error: 'str' is a private member of 'Mystring'
for the lines
char *buff = new char[std::strlen(obj.str)+1];
std::strcpy(buff, obj.str);
I can't seem to see why.
I know that as I am declaring the friends of the function, they are now able to access the private string pointer, *str
yet the error still persists. The concatenation operator +
functions as normal but I can't work out why the error above persists.
Why is this error being yielded?