【问题标题】:resizing string members in constructor在构造函数中调整字符串成员的大小
【发布时间】:2017-01-10 19:27:46
【问题描述】:

我必须确保在构造过程中字符串成员的大小是固定的。但是,它们可以在构建完成后增加它们的大小,然后在程序中,用户选择向其添加更多文本。

class A {
    std::string name;
    std::string desc;
    int num;

  public:
    A(int, std::string, std::string);
    .....
}

现在如果我这样做 -

A(int n, std::string name, std::string d) : 
    num(n),
    name(name),
    desc(d) 
{
    ....
}

我必须在构造函数体内调用resize()。这意味着在构建过程中的某个时间存在完整的字符串长度。假设我希望初始大小为 5,并且用户传递 20 个字符的字符串,在构造期间和 resize() 之前,字符串将包含 20 个字符,对吗?

现在我正在考虑这样做 -

A(int n, std::string name, std::string d) : 
    num(n)
{
    name = name;
    desc = d;
    name.resize(5);
    desc.resize(5);
    ....
}

但这也一样吧?

我应该在传递的参数本身上调用resize() 吗?或者有没有更好的方法..

【问题讨论】:

  • 为什么要调整字符串的大小?
  • name( name.substr(0, 5) ), 之类的怎么样?
  • 实际上您想在调用构造函数时截断输入字符串并复制到变量成员中?
  • 我想你的意思是reserve?
  • @JoachimPileborg 那么这里最好的方法是什么。移动然后剪切变量,忽略空参数或最高投票的答案建议 atm。

标签: c++ string c++11 constructor


【解决方案1】:

这样的构造函数怎么样:

A::A(int n, const std::string &name, const std::string &d) :
    n(n), name(name, 0, 5), d(d, 0, 5)
{
}

永远不会复制字符串的完整长度。它们是通过引用获取的,并且副本最多使用前 5 个字符构成。

它使用substring constructor(3 号)。

【讨论】:

    【解决方案2】:

    您可以执行以下操作

    class A 
    {
    private:    
        int num;
        std::string name;
        std::string desc;
        static const size_t INITIAL_SIZE = 5;
    public:
        A( int num, const std::string &name, const std::string &desc )
            : num( num ), 
              name( name.substr( 0, INITIAL_SIZE ) ), 
              desc( desc.substr( 0, INITIAL_SIZE ) )
        {
            //
        }       
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-01
      • 2011-12-07
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 2012-01-10
      • 1970-01-01
      • 2017-01-14
      相关资源
      最近更新 更多