0

私は C++ プログラミングの初心者で、cin を使用して構造体を引数として関数に渡す方法を知りたいと思っています。

コードの考え方は、ユーザーから構造体の名前を入力し、その名前を関数に渡すことです。これが私が遊んでいたものです:

   class myPrintSpool
    {
    public:
        myPrintSpool();
        void addToPrintSpool(struct file1);
    private:
        int printSpoolSize();
        myPrintSpool *printSpoolHead;
    };

    struct file1
   {
        string fileName;
        int filePriority;
        file1* next;

   };

    int main()
    {
        myPrintSpool myPrintSpool; 
        myPrintSpool.addToPrintSpool(file1);
    return 0; 
    } 

これでビルド可能。ただし、次の行に沿ってもっと何かが必要でした。

 class myPrintSpool
    {
    public:
        myPrintSpool();
        void addToPrintSpool(struct fileName);
    private:
        int printSpoolSize();
        myPrintSpool *printSpoolHead;
    };

    struct file1
   {
        string fileName;
        int filePriority;
        file1* next;

   };

    int main()
    {
        string fileName; 
        cout << "What is the name of the file you would like to add to the linked list?"; 
        cin >> fileName; 

        myPrintSpool myPrintSpool; 
        myPrintSpool.addToPrintSpool(fileName);
    return 0; 
    } 

誰かが私がこれを行う方法を助けることができますか? 前もって感謝します!

4

1 に答える 1

0

この種のメタプログラミングは、一般に、C++ では非常に高度です。その理由は、インタープリター言語とは異なり、ソース ファイルに存在するものの多くがファイルのコンパイル時に失われるためです。実行可能ファイルでは、文字列file1がまったく表示されない場合があります。(実装に依存していると思います)。

代わりに、何らかの検索を行うことをお勧めします。たとえば、fileName で渡された文字列を各構造体の と比較しfileNameたり、任意のキーを構造体に関連付けたりすることができます。たとえば、 を作成し、std::map<string, baseStruct*>すべての構造体 (file1、file2 など) を からbaseStruct継承した場合、渡された文字列に関連付けられている構造体をマップで検索できます。異なるタイプの構造体をマップに挿入するにはポリモーフィズムが必要になるため、継承は重要です。

他にももっと高度なトピックがたくさんありますが、これは一般的な考え方です。実行時に文字列から型をインスタンス化しようとするよりも、何らかのルックアップを行うのが最も簡単です。これは、基本的に同じことを行うための、より厳密で保守しやすいアプローチです。

編集:「file1」と呼ばれる構造体のタイプが1つしかないことを意味し、それをインスタンス化してaddToPrintSpoolに渡したい場合、それは私の以前の回答とは異なります(たとえば、file1と呼ばれる複数の構造体が必要な場合に適用されます)文字列から動的にを割り出すのは難しいですが、既知の型のインスタンスに文字列を設定するのは簡単です。)

file1youのインスタンスをインスタンス化して使用するには、次のようにします。

//In myPrintSpool, use this method signature.
//You are passing in an object of type file1 named aFile;
//note that this object is _copied_ from someFile in your
//main function to a variable called aFile here.
void addToPrintSpool(file1 aFile);
...
int main()
{
    string fileName; 
    cout << "What is the name of the file you would like to add to the linked list?"; 
    cin >> fileName; 

    //Instantiate a file1 object named someFile, which has all default fields.
    file1 someFile;
    //Set the filename of aFile to be the name you read into the (local) fileName var.
    someFile.fileName = fileName;

    myPrintSpool myPrintSpool; 
    //Pass someFile by value into addToPrintSpool
    myPrintSpool.addToPrintSpool(someFile);
    return 0; 
} 
于 2013-01-16T00:58:51.753 に答える