Jqmfg
Jqmfg

Reputation: 141

Get arrays from other classes

I am working on a Ludum Dare project and I can't figure out how to use an array in another class for using a tilesheet. What is the best way to store an array in another class and then use it in the main.cpp file?

Upvotes: 0

Views: 747

Answers (2)

Chris O
Chris O

Reputation: 5037

One way to do this is to use the STL vector class as your array. In the below sample, the nNumbers vector is of type int and a copy is made through a public get accessor method that ClassB uses.

// ClassA.h
#include <vector>

class ClassA
{
public:
    ClassA();

    std::vector<int> getNumbers();

private:
    std::vector<int> mNumbers;
};


// ClassA.cpp
#include "stdafx.h"
#include "ClassA.h"

ClassA::ClassA()
{
    for(int i = 0; i < 5; i++)
    {
        mNumbers.push_back(i);
    }
}

std::vector<int> ClassA::getNumbers()
{
    return mNumbers;
}


// ClassB.cpp
#include "stdafx.h"
#include "ClassB.h"
#include "ClassA.h"

#include <vector>
#include <iostream>

void ClassB::runOutput()
{
    ClassA A;
    std::vector<int> someNumbers = A.getNumbers();
    for(unsigned int i = 0; i < someNumbers.size(); i++)
    {
        std::cout << "i = " << i << std::endl;
    }
}

Upvotes: 1

darmat
darmat

Reputation: 728

Declare the data structure in the class, create an object and access the it! You also might want to read more about passing by reference to a function...

Upvotes: 0

Related Questions