I am trying to iterate through an array to objects to set different attributes of those objects. The attributes of my objects may change over time.
My code as a simplified example:
// MyClass.h
class MyClass
{
/* class definitions */
};
extern MyClass object;
// MyClass.cpp
#include MyClass.h
/* Constructors, Destructors, Functions */
// main.cpp
void reload_objects();
int main()
{
MyClass object[20];
reload_objects();
{
void reload_objects();
{
for (int i = 0; i < 20; i++){
object[i].setProperties(/*args*/);
}
}
I am getting an error error: No match for 'operator[]' (operand types are ‘MyClass’ and ‘int’)
. If I move the for loop into main it compiles and runs fine.
What is causing this error?
Would it be easier or in some way better to use std::vector<MyClass> object(20)
in some way?
There are several mistakes in your given code snippet. You can correct them as i have shown below. I have added comments wherever i have made changes.
MyClass.h
#ifndef MYCLASS_H
#define MYCLASS_H
// MyClass.h
class MyClass
{
/* class definitions */
public:
MyClass() = default;
};
extern MyClass object[20]; //declare object as an array
#endif
MyClass.cpp
// MyClass.cpp
#include "MyClass.h"
/* Constructors, Destructors, Functions */
main.cpp
#include <iostream>
#include "MyClass.h"
MyClass object[20]; // define object here instead of inside main()
void reload_objects(); // reload_objects() doesnt take any argument by looking at its call and definiton
int main()
{
// MyClass object[20]; //don't define object here
reload_objects();
}
void reload_objects() //you had a semicolon here so i removed it
{
for (int i = 0; i < 20; i++){
object[i].setProperties(/*args*/);
;
}
}
Also don't forget to add the definition and declaration of your other member functions like setProperties in the above example for it to work. These are some of the changes that i made:
object
as an array of size 20 inside MyClass.h.object
outside of main() inside main.cpp as i did in my example.Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments