修复QString大小(长度)

时间:2014-01-24 14:14:41

标签: c++ string qt qstring

出于某种原因,我需要使用固定大小的字符串。现在我正在寻找一个QString类。
但是我有一些问题让QString对象具有恒定的大小。
例如,我想要大小为10的字符串,这意味着,如果我尝试在其中写入超过100个字符的字符串,它将在100之后剪切所有字符。 我在Qt文档中找到了QString的构造函数,但我不确定它是否会像我说的那样工作

  • QString(int size,QChar ch)

在这种情况下你能提出什么建议?

1 个答案:

答案 0 :(得分:1)

您可以拥有具有字符串的包装类,但不是字符串,但可以在可以使用QString的任何地方使用它。它也可以与所有QString的方法和运算符一起使用,只要您将其视为指针即可。

#include <QString>

class FixedWidthString {
  mutable QString m_string;
  //! Ignored if negative.
  int m_maxLength;
  inline const QString& data() const {
      if (m_maxLength >= 0 && m_string.length() > m_maxLength)
          m_string.truncate(m_maxLength);
      return m_string;
  }
  inline QString& data() {
      if (m_maxLength >= 0 && m_string.length() > m_maxLength)
          m_string.truncate(m_maxLength);
      return m_string;
  }
public:
  explicit FixedWidthString(int maxLength = -1) : m_maxLength(maxLength) {}
  explicit FixedWidthString(const QString & str, int maxLength = -1) : m_string(str), m_maxLength(maxLength) {}
  operator const QString&() const { return data(); }
  operator QString&() { return data(); }
  QString* operator->() { return &data(); }
  const QString* operator->() const { return &data(); }
  QString& operator*() { return data(); }
  const QString& operator*() const { return data(); }
  FixedWidthString & operator=(const FixedWidthString& other) {
      m_string = *other;
      return *this;
  }
};

int main() {
    FixedWidthString fs(3);
    FixedWidthString fs2(2);
    *fs = "FooBarBaz";
    Q_ASSERT(*fs == "Foo");
    fs->truncate(2);
    Q_ASSERT(*fs == "Fo");
    fs->append("Roo");
    Q_ASSERT(*fs == "FoR");
    fs->truncate(1);
    *fs += "abc";
    Q_ASSERT(*fs == "Fab");
    fs2 = fs;
    Q_ASSERT(*fs2 == "Fa");
}