在BST中使用c++使用Object文件的函数

Using functions of an Object file using C++ in a BST

本文关键字:Object 文件 函数 使用 c++ BST      更新时间:2023-10-16

我正在制作一个二叉搜索树,我在一个。cpp文件中有以下函数:

void MovieTree::printMovieInventory(MovieNode* node)
{
    if(node)
    {
        while(node->rightChild && node->leftChild)
        {
            std::cout<<"Movie:"<<node->title<<" "<<node->quantity<<std::endl;
            if(node->rightChild)
            {
                printMovieInventory(node->rightChild);
            }
            if(node->leftChild)
            {
                printMovieInventory(node->leftChild);
            }
        }
    }
    else
    {
        std::cout<<"No movies in list!"<<std::endl;
    }

我有点不确定我应该如何在我的main.cpp文件或"驱动程序文件"中引用这个函数。我在main中使用如下方式引用它:

            case 3: //message is read in from file
              {
                MovieTree::printMovieInventory(node);
              }
                break;

然而,在引用this时,它只是抛出一个错误:

Driver.cpp:37:40: error: cannot call member function 'void MovieTree::printMovieInventory(MovieNode*) without object
MovieTree::printMovieInventory(node);

不知道这是什么意思。

完整main:

int main(int argc, char **argv)
{
    bool quit = false;
    string s_input;
    int input;
    // loop until the user quits
    while (!quit)
    {
        MovieNode* node = new MovieNode;
        printOptions();
        // read in input, assuming a number comes in
        getline(cin, s_input);
        input = stoi(s_input);
        switch (input)
        {
            // print all nodes
            case 1:     //rebuild network
                break;

                break;
            case 3: //message is read in from file
              {
                MovieTree::printMovieInventory(node);
              }
                break;
            case 4:     // quit
                quit = true;
                cout << "Goodbye!"<< endl;
                break;
            default:    // invalid input
                cout << "Invalid Input" << endl;
                break;
        }
    }
}

您需要一个MovieTree实例。在代码的某处,在switch语句的上方,您应该添加:

MovieTree movieTree;

,然后你的switch语句看起来像这样:

case 3: //message is read in from file
                movieTree.printMovieInventory(node);
                break;

或者,如果MovieTree没有状态(即。没有字段或它所依赖的其他函数),您可以将printMoviewTree标记为static,而不是上面的代码。