2013-01-16 5 views
0

저는 C++ 프로그래밍의 초보자이며 cin을 사용하는 함수에 인수로 struct를 전달하는 방법에 대해 궁금합니다.구조체를 매개 변수로 함수에 전달

코드 아이디어는 사용자로부터 구조체의 이름을 입력하고 해당 이름을 함수에 전달하는 것입니다. 다음과 같이 놀았습니다.

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

사람이 내가이 일에 대해 갈 것 어떻게 도와 드릴까요 : 그러나, 나는의 라인을 따라 더 뭔가를 원했다? 미리 감사드립니다!

답변

0

이러한 종류의 메타 프로그래밍은 일반적으로 C++에서 매우 발전되었습니다. 그 이유는 해석 된 언어와 달리 소스 파일에있는 대부분이 파일을 컴파일 할 때 손실됩니다. 실행 파일에서 문자열 file1이 전혀 표시되지 않을 수 있습니다! (그것은 구현에 의존적이다, 나는 믿는다).

대신에 일종의 조회를하는 것이 좋습니다. 예를 들어, fileName에 전달 된 문자열을 각 구조체의 fileName과 비교하거나 모든 키를 구조체와 연결할 수 있습니다. 예를 들어 을 생성하고 모든 구조체 (예 : file1, file2, ...)를 baseStruct에서 상속받은 경우 전달 된 문자열과 연결된 구조체를지도에서 조회 할 수 있습니다. 서로 다른 유형의 구조체를 맵에 삽입하려면 다형성이 필요하기 때문에 상속이 중요합니다.

우리가 얻을 수있는 많은 다른 고급 주제가 있지만, 이는 일반적인 아이디어입니다. 런타임에서 유형을 문자열로 인스턴스화하는 대신 일종의 조회를 수행하는 것이 가장 간단합니다. Here은 기본적으로 동일한 작업을 수행하는 데있어보다 엄격하고 유지 관리가 쉬운 방법입니다.

EDIT : 'file1'이라는 구조체의 유형이 하나 뿐이며 인스턴스화하여 addToPrintSpool에 전달하려는 경우 이는 이전 답변과 다릅니다 (예를 들어, 파일 1과 파일 2 및 사용할 구조체 추론 할라고 여러 구조체가. 동적 문자열에서 유형을 알아내는 것은 어렵다,하지만 알려진 유형의 인스턴스에 문자열을 설정 간단합니다.)

하는 인스턴스화하기 의 인스턴스를 사용할 수 있습니다.

//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; 
} 
+0

도움 주셔서 감사합니다. :) –

관련 문제