【问题标题】:Passing a Struct as a Parameter to a Function将结构作为参数传递给函数
【发布时间】:2013-01-16 00:53:49
【问题描述】:

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

谁能帮我做这件事?提前致谢!

【问题讨论】:

    标签: function pointers parameters struct arguments


    【解决方案1】:

    一般来说,这种元编程在 C++ 中非常先进。原因是,与解释语言不同,源文件 中存在的大部分内容在文件编译时都会丢失。在可执行文件中,字符串file1 可能根本不会出现! (我相信它取决于实现)。

    相反,我建议进行某种查找。例如,您可以将在 fileName 中传入的字符串与每个结构的fileName 进行比较,或者您可以将任何键与您的结构相关联。例如,如果您创建了 std::map&lt;string, baseStruct*&gt; 并从 baseStruct 继承了所有结构(例如 file1、file2、...),那么您可以在映射中查找与传入字符串关联的结构。继承很重要,因为您需要多态性才能将不同类型的结构插入映射中。

    还有许多其他更高级的主题可供我们讨论,但这是大体思路。进行某种查找而不是尝试在运行时从字符串实例化类型是最简单的。 Here 是一种更严格、更易于维护的方法来做基本相同的事情。

    编辑:如果您的意思是您只有一种名为“file1”的结构,并且您想要实例化它并将其传递给 addToPrintSpool,这与我之前的答案不同(例如,如果您想要多个结构称为 file1 和 file2 并想推断使用哪个结构。从字符串中动态找出 types 很困难,但是将字符串设置为 known type 的实例是直截了当。)

    要实例化和使用file1 的实例,您可以这样做:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-04
      • 2020-04-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-17
      相关资源
      最近更新 更多