简体   繁体   中英

Arduino object constructor in class sets rubbish values

I am currently trying to create a class that has a member object with a non-default constructor for an Arduino project. The object is a pointer so that I can construct when MyClass is constructed (MyObjClass *my_obj;)

// MyObjClass:
class MyObjClass(){
    const int param;
public: 
    MyObjClass(const int param): param(param){ ... }
};

// MyClass:
class MyClass(){
     MyObjClass *my_obj;
public:
     MyClass::MyClass(const int param): my_obj(param){ ... }
};

It builds fine, but the value param in my_obj is rubbish (random value). Does it already initialize the object before the constructor call? My workaround is to use no const values but there must be a better way (the right way).

You are holding pointer to MyObjClass and try to init him with some int , the right way will be my_obj(new MyObjClass(param)) .

Also I would suggest to use smart pointers to avoid memory leaks.

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