C++ classes - how to pass vector of custom type to function
I am attempting to develop a class with a function that can take a vector of items as it's argument.
I can get it to work fine if I use a vector of type int, or other primitive, but开发者_Python百科 I can't get it to work with a vector of objects.
eg:
In my header file:
int influenceParticles(vector<Particle> particles);
This is what I am after, but won't compile (error stated is "'Particle' was not declared in this scope"
).
The particle.h file has been included at the top of this header file.
Clarification
Here is the .h file that gives me the error
#ifndef _PARTICLE_ATTRACTOR
#define _PARTICLE_ATTRACTOR
#include "ofMain.h"
#include "particle.h"
class ParticleAttractor {
//private
public:
ParticleAttractor(int posX, int posY); //constructor (void)
int influenceParticles(vector<Particle> particles);
};
#endif
Maybe you have cyclic includes, ie. if the ParticleAttractor.h also includes the Particle.h. To solve this, you should make a forward declaration of Particle in ParticleAttractor.h:
class Particle;
You should also consider passing the vector by reference to avoid copying:
int influenceParticles(vector<Particle>& particles);
First Particle
must be a defined type. This definition should work:
int influenceParticles(vector<vector<int> > particles);
For practice, it is better to use the by reference parameter type rather than by value. So it is better to define it as:
int influenceParticles(vector<vector<int> >& particles);
精彩评论