0

我正在製作一個程序,用於加密和解密使用2D表格的文本短語。我有一個單獨的類,它包含密碼所需的所有內容。但是,在處理桌子時我遇到了麻煩。我已經把它構建得夠好了,但是我很難將它封裝在課堂上。我覺得應該在創建對象時自動構建它,但現在我不得不通過main調用它。如何將數組作爲私有類成員並確保正確封裝?

#include <iostream> 
#include <string> 
using namespace std; 

class Cipher { 
    public: 
     Cipher(); 
     Cipher(string key); 
     Cipher(string key, string message); 

     void buildTable(char table[][26]); 
     void newKey(string keyphrase); 
     void inputMessage(); 
     string encipher(string message); 
     string decipher(string message); 
     string getPlainText() const; 
     string getCipherText() const; 

    private: 
     string key; 
     string plaintext; 
     string ciphertext; 
}; 

。 。 。 。

void Cipher::buildTable(char table[][26]) { 
    char alphabet[26] = {'a','b','c','d','e','f','g','h','i','j','k','l','m', 
         'n','o', 'p','q','r','s','t','u','v','w','x','y','z'}; 

    int alphaIndex = 0; 

    for (int index1 = 0; index1 < 26; index1++) { 
     for (int index2 = 0; index2 < 26; index2++) { 

      if ((index1 + index2) < 26) { 
       alphaIndex = index1 + index2; 
       table[index1][index2] = alphabet[alphaIndex]; 
      } 
      else 
       alphaIndex = 0; 

      while (((index1 + index2) > 25) && index2 < 26) { 
       table[index1][index2] = alphabet[alphaIndex]; 
       index2++; 
       alphaIndex++; 
      }   
     }    
    } 
} 

此表是程序運行的關鍵,並且沒有理由改變它。我試圖將其作爲私人成員加入,但遇到了很多麻煩。我是否應該在構造函數中包含這個,或者封裝它的正確方法是什麼?

+0

我說用PIMPL方法使實現私有。 http://stackoverflow.com/questions/60570/why-should-the-pimpl-idiom-be-used雖然我很困惑,當你讓你的表私人時,你有什麼問題。 – drescherjm

+0

據我所知,該表應該在程序調用時保持不變,並在Cipher類的所有實例中共享,對吧? – user3159253

+2

絕對應該是私人會員。你遇到什麼麻煩? –

回答

0

您所擁有的「char table [] [26]」,我建議讓它成爲您班級的私人成員。而當在構造函數中,你應該初始化它。你的「buildTable」成員函數不應該把數組作爲參數,而應該初始化你的私有二維數組。通過查看你的代碼,我沒有看到任何理由爲什麼你應該在「buildTable」函數堆棧上放置你的表。

+0

謝謝,我會試試這個。 – Victor

+0

我想我昨天只是盯着這個太久了。我把整個表格構造放在構造函數中,並且運行良好。感謝您的幫助 – Victor

+0

好吧,我不會推薦使構造函數如此之大。相反,讓你的數組初始化在一個私有的「init」函數中,並從你的構造函數調用「init」函數 – armanali

0

這看起來像是Initialize On First Use功能的作業。

class Cipher { 
    public: 
     // ... 
    private: 
     using table_type = char[26][26]; 
     // Or for C++03 mode, 
     // typedef char table_type[26][26]; 

     static void buildTable(table_type& table); 
     static const table_type& getTable(); 
     // ... 
} 

const Cipher::table_type& Cipher::getTable() { 
    static table_type the_table; 
    if (the_table[0][0] == '\0') 
     buildTable(the_table); 
    return the_table; 
} 
0

我寧願留下構造函數參數來輸入最小的類配置值。所以我會把它作爲一個私人成員。至於值,我不明白爲什麼每次創建實例時重新計算它們,如果它們不會更改,只需計算一次,然後將它們硬編碼到cpp文件中。

的* .h文件中:

class Cipher { 
    ... 
private: 
    ... 
    static const int table[26][26]; 
}; 

的* .cpp文件:

... 
const int Cipher::table[26][26] = { ... }; 
... 
相關問題