Reputation: 91
I have this class defined:
class Forum{
std::string title;
Thread* threads[5];
and in the constructor of Forum::Forum I want to pass a string argument to define title(which is of type-string)
Forum::Forum(string *k) {
int i;
std::strcpy(&title.c_str(),k->c_str());
I have problems in that.In this code i get an "lvalue required as unary '&' operand" error. If i erase '&' i get the error " invalid conversion from 'const char*' to 'char*' [-fpermissive]".
Any ideas how I will manage to pass the argument with strcpy(or with another method maybe) to a string type avoiding the above errors?
Upvotes: 1
Views: 111
Reputation: 44828
You should definitely learn a bit more about the Standard Library. In C++ you can assign one std::string
to another without messing with pointers and strcpy
.
Forum::Forum(const std::string& k) {
// int i; you aran't using this anywhere, so why declare it?
// as pointed out by @EdHeal, this-> is not necessary here
/*this->*/ title = k;
}
Upvotes: 0
Reputation: 59997
You do not need to use strcpy
- as this will not work
Use the strings assignment operator
i.e.
Forum::Forum(string *k) {
title = *k;
}
Or better still
Forum::Forum(const string& k) {
title = k;
}
Or perhaps initialisation lists
Forum::Forum(const string& k) : title(k) { }
The latter being the best
Upvotes: 3
Reputation: 44181
Unless you intend to allow the title to be omitted, I would recommend you pass a const
reference instead of a pointer:
Forum::Forum(const string& k)
This makes it more clear that the name must be provided and also allows passing a string literal as the name:
Forum f("Main Forum");
Then, to copy a std::string
, simply assign it or use its copy constructor. strcpy
is only for C-style char*
strings. In this case, use a member initializer:
Forum::Forum(const string& k):
title(k)
{
}
Upvotes: 7