简体   繁体   中英

Passing Vector from one class to another for manipulation

I want to get the vector

std::vector< std::vector<int> > Ticket; 

from one class (User) to another (Game) in order to manipulate the contents there.

Specifically I need it in a function (compareNumbers).

Currently in main.cpp I have this code:

#include "User.h"
#include "Game.h"

int k = game.compareNumbers(user.<int>Ticket);

(unnecessary includes and other code left out for simplicity)

In User.h is the declaration for for the vector (public) and in User.cpp the Vector is populated.

I suspect it is more complicated due it being a vector containing vectors but I'm not sure.

In Game.cpp I have

int Game::compareNumbers(std::vector< std::vector<int> > Ticket)
// Some code

The error that I am presented with is 'expected a member name' on the first < in main. However I suspect that there are more errors than that.

Also I think maybe I should be passing by reference, but I'm not sure. and I'm not sure how to do that, and possibly const aswell, in compareNumbers, I am not modifying the vector, purely comparing its contents with the contents of another vector, again, not sure?

Assuming your user has a member Ticket , you can pass this object to your Game::compareNumbers() function just using

int = game.compareNumbers(user.Ticket);

As things are declared, this will copy the std::vector<std::vector<int> > , however, which is probably not quite what you want. If you really just want to look at the numbers (the name of the function indicates you kind of do), you'd pass the object using a const& :

int Game::compareNumbers(std::vector<std::vector<int> > const& Ticker) {
    // ...
}

If compareNumbers() actually needs to modify its argument, you'd omit the const but keep the reference: without the reference a copy is passed on and modified which wouldn't affect the original user.Ticket object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM