2016-01-13 72 views
0

我試圖將std::string變量轉換爲FixedString。我真的不明白如何處理這個問題。該代碼已經過測試並可正常工作。我只是不知道將變量std::string test轉換爲FixedString text如何從字符串(C++)填充FixedString?


#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; 
} 

謝謝。

+0

你可以用'的strcpy()'和'的std :: string :: c_str()'。請特別指出你的問題?你介意改善你的問題嗎? –

回答

3

如何在您的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

+0

謝謝@πάνταῥεῖ我正在測試它。對不起,花了這麼長時間纔回答。 –

+1

@HaniGoc看我的演示。 –