【问题标题】:Passing a string argument to another string将字符串参数传递给另一个字符串
【发布时间】:2016-01-04 14:21:15
【问题描述】:

我已经定义了这个类:

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

在 Forum::Forum 的构造函数中,我想传递一个字符串参数来定义标题(属于字符串类型)

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

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

任何想法我将如何设法将参数与 strcpy(或可能使用另一种方法)传递给字符串类型以避免上述错误?

【问题讨论】:

    标签: c++ string


    【解决方案1】:

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

     Forum::Forum(const string& k)
    

    这更清楚地表明必须提供名称,并且还允许将字符串文字作为名称传递:

     Forum f("Main Forum");
    

    然后,要复制std::string,只需分配它或使用它的复制构造函数。 strcpy 仅适用于 C 风格的 char* 字符串。在这种情况下,使用成员初始化器:

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

    【讨论】:

      【解决方案2】:

      您不需要使用strcpy - 因为这不起作用

      使用字符串赋值运算符

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

      或者更好

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

      或者也许是初始化列表

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

      后者是最好的

      【讨论】:

        【解决方案3】:

        您绝对应该更多地了解标准库。在 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; 
        }
        

        【讨论】:

        • 您不需要this->int i,因为从未使用过i
        • @EdHeal,也许这是实际使用i的代码的一部分......虽然你是对的
        • std::string 不是 STL 的一部分。 STL 是容器、迭代器和算法。不幸的是,当“标准库”完全足够且更具描述性时,有一种趋势是使用“STL”作为“标准库”的简写。
        猜你喜欢
        • 1970-01-01
        • 2018-12-13
        • 2021-05-21
        • 1970-01-01
        • 2012-04-21
        • 2021-12-12
        • 1970-01-01
        • 1970-01-01
        • 2016-03-16
        相关资源
        最近更新 更多