简体   繁体   中英

Passing a string argument to another string

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?

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)
{
}

You do not need to use strcpy - as this will not work

Use the strings assignment operator

ie

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

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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM