繁体   English   中英

将字符串参数传递给另一个字符串

[英]Passing a string argument to another string

我定义了此类:

class Forum{
std::string title;
Thread* threads[5];

在Forum :: Forum的构造函数中,我想传递一个字符串参数来定义title(类型为string)

Forum::Forum(string *k) {
int i;
std::strcpy(&title.c_str(),k->c_str());

我在那儿有问题。在这段代码中,我收到“一元'&'操作数所需的左值”错误。 如果我删除'&',则会收到错误“从'const char *'到'char *'[-fpermissive]的无效转换”。

有什么想法可以避免上述错误,我将如何使用strcpy(或其他方法)将参数传递给字符串类型?

除非打算省略标题,否则建议您传递const引用而不是指针:

 Forum::Forum(const string& k)

这使得必须提供名称更加明确,并且还允许传递字符串文字作为名称:

 Forum f("Main Forum");

然后,要复制std::string ,只需分配它或使用其复制构造函数即可。 strcpy仅适用于C样式char*字符串。 在这种情况下,请使用成员初始化程序:

Forum::Forum(const string& k):
  title(k)
{
}

您不需要使用strcpy这将无法正常工作

使用字符串赋值运算符

Forum::Forum(string *k) {
    title = *k; 
}

还是更好

Forum::Forum(const string& k) {
    title = k; 
}

也许初始化列表

Forum::Forum(const string& k) : title(k) { }

后者是最好的

您绝对应该了解有关标准库的更多信息。 在C ++中,您可以将一个std::string分配给另一个,而不会弄乱指针和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; 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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