I'm trying to include a member variable in the class I write,
MyClass.h
#include <SomeClass.h>
Class MyClass{
public:
MyClass(int par);
SomeClass B;
}
MyClass.cpp
#include "MyClass.h"
#include "SomeClass.h"
MyClass::MyClass(int par){
B=SomeClass(par);
}
However SomeClass
takes variables for its constructor, so the above code yields no matching function for call to "SomeClass::SomeClass()"
What should I do here?
Update: Seems like member initializer list is the way to go, but how if I want to use an array of SomeClass
objects? So MyClass.h becomes:
#include <SomeClass.h>
Class MyClass{
public:
MyClass(int par);
SomeClass B[2];
}
use member initializer list
MyClass::MyClass(int par) : B(par)
{
}
You can't quite get what you want, but you can get what you need. To provide array access to the set of objects, create an array of pointers
Class MyClass {
public:
MyClass(int par);
SomeClass B0;
SomeClass B1
SomeClass* B[2];
Then initialize the pointers in your constructor:
MyClass::MyClass(int par) :
B0(123), B1(456)
{
B[0] = &B0;
B[1] = &B1;
}
This is clearly tedious for more than a small number of objects, but fine for anything you are likely to do on a microcontroller. Now you have an array of object pointers that can be used as you need:
for(i=0; i<2; i++) {
B[i]->foo();
}
Note that you are consuming additional memory for a pointer to each 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.