我正在尝试将 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;
}
关于c++ - 如何从字符串(c++)填充 FixedString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34769073/