c++ - 如何从字符串(c++)填充 FixedString?

标签 c++ string

我正在尝试将 std::string 变量转换为 FixedString。我真的不明白如何处理这个问题。该代码已经过测试并且可以正常工作。我只是不知道将变量 std::string test 转换为 FixedString text


#include <iostream>

using namespace std;

static const int MAX_KEY_LEN = 16;

class FixedString 
{ 
  public:
    char charStr[MAX_KEY_LEN];

    bool operator< (const FixedString& fixedString) const {
        return std::lexicographical_compare(charStr, charStr + MAX_KEY_LEN,
            fixedString.charStr, fixedString.charStr +MAX_KEY_LEN);
    }

    bool operator==(const FixedString& fixedString) const {
        return std::equal(charStr, charStr+MAX_KEY_LEN, fixedString.charStr);
    }

    bool operator!=(const FixedString& fixedString) const {
        return !std::equal(charStr, charStr+MAX_KEY_LEN, fixedString.charStr);
    } 
};

struct comp_type : public std::less<FixedString>
{
    static FixedString max_value()
    {
        FixedString s;
        std::fill(s.charStr, s.charStr+MAX_KEY_LEN, 0x7f);
        return s;
    } 
};

int main(int argc, char* argv[])
{
   FixedString s;
   string test = "hello";
    //how to convert string test to FixedString test???
   return 0;
}

谢谢。

最佳答案

如何向您的 FixedString 类添加适当的转换构造函数和赋值运算符?

 class FixedString 
 { 
 public: 
      char charStr[MAX_KEY_LEN];
      FixedString(const std::string& s)
      {
           // Maybe add some checks and ecxeptions
           strncpy(charStr,s.c_str(),MAX_KEY_LEN);
      }

      FixedString& operator=(const std::string& s)
      {
           // Maybe add some checks and ecxeptions
           strncpy(charStr,s.c_str(),MAX_KEY_LEN);
           return *this;
      }

      // ...
};

像这样使用它

int main(int argc, char* argv[])
{
   FixedString s1;
   string test1 = "hello";
   s1 = test1; // <<< call overloaded assignment operator

   string test2 = "world";
   FixedString s2(test2); // <<< call overloaded constructor
   return 0;
}

Quickly scribbled demo here

关于c++ - 如何从字符串(c++)填充 FixedString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34769073/

相关文章:

c# - 检查字符串是否排序

c# - 更改文本 block 中部分文本的颜色

python - 如何使用 isupper( ) 方法在 Python 中只打印大写字母?

c++ - Windows 生成文件(名称)- 语法错误 : ')' missing in macro invocation

c++ - 什么是 R6010 错误?

c - 将输入文件标记为链表

Java JTextField 写入时转换为大写/小写

C++ 重载赋值运算符

c++ - QGraphicsScene : OpenGL with fallback

c++ - C 编程一元运算符优先级