Member variable needs parameters for constructor

2020-04-12 14:11发布

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];
}

2条回答
Melony?
2楼-- · 2020-04-12 14:28

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.

查看更多
不美不萌又怎样
3楼-- · 2020-04-12 14:46

use member initializer list

MyClass::MyClass(int par) : B(par)
{
}
查看更多
登录 后发表回答