开发者

C++ - Access array (in main) from methods outside main

I have an array in my main class that holds objects that I need to print out for a menu listing. The array is declared and initialized in main. I need to, however, access the same array in a sub-menu function. If I copy the code (for loop that prints out the values) to the sub-menu, nothing is printed (presumably because it can't access the original array and has made a new, blank one). Is there any way (without making the array a global variable) that I can access the array in this sub-menu? Both the main and the sub-menu function are in the same file and the sub-menu is called from main.

Maybe to put it more simply, can I use scope resolution to 开发者_如何学运维bring me up one 'level' in scope?


You could pass the array in as an additional argument to the function.


If I understand your question correctly, you have an array in one function you need accessed in another function?

Pass the array into the second function as a const reference.

#include <iomanip>
#include <iostream>
#include <vector>

using std::vector;
using std::cout;
using std::endl;

void print(const vector<int> &array)
{
        for (int i = 0; i != array.size(); ++i)
        {
                cout << array[i] << " ";
        }

        cout << endl;
}

int main()
{
        vector<int> myArray;
        myArray.push_back(0);
        myArray.push_back(1);
        myArray.push_back(2);
        myArray.push_back(3);
        myArray.push_back(4);
        myArray.push_back(5);

        print(myArray);

        return 0;
}


Believe me this is the dirtiest code I have ever written.
C++ - Access array (in main) from methods outside main

#include<iostream>
using namespace std;

void foo();

int main(int argc, char* argv[],bool yes,int* arr=NULL)
{
    cout << "Inside Main"<<endl;

    if(0 != yes)
    {
        foo();
    }
    else
    {
        cout<<"Got that array at : "<< &arr <<endl;
    }

    return 0;
}

void foo()
{
    cout << "Inside Foo"<<endl;

    int billy [5] = { 16, 2, 77, 40, 12071 };

    main(0,NULL,false,billy);
}

NOTE:MBennett's answer is good. +1


I would try to pass the the sub-menu a pointer to the object as argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜