c++ - Pass existing object to constructor or construct a new one -


the easiest way me explain example of i'm trying in language im more familiar with, c#:

public class serverlib {     private softwareserial _bt;     private string _name, _game;      public serverlib(int rx, int tx, string name, string game) {         _bt = new softwareserial(rx, tx);         _bt.begin(9600);         _name = name;         _game = game;     }      public serverlib(ref softwareserial bt, string name, string game) {         _bt = bt;         _name = name;         _game = game;     } } 

i'm attempting in arduino library (so assume c++) , have tried following things:

class serverlib {     public:         serverlib(int rx, int tx, string name, string game);         serverlib(softwareserial serial, string name, string game);     private:         softwareserial _bt;         string _name;         string _game; };   serverlib::serverlib(int rx, int tx, string name, string game) : _bt(rx, tx) {     _name = name;     _game = game;      _bt.begin(9600); }  serverlib::serverlib(softwareserial serial, string name, string game) : _bt(serial) {     _name = name;     _game = game; } 

this compiles first constructor works, if use second 1 attempts @ using softwareserial seem nothing. if comment out first constructor , replace second 1

serverlib::serverlib(softwareserial& serial, string name, string game) : _bt(serial) {} 

and change field softwareserial& _bt constructor work fine, cannot manage compile both constructors. if keep error:

error: invalid initialization of reference of type 'softwareserial&' expression of type 'int' 

changing first constructor

serverlib::serverlib(int rx, int tx, string name, string game) : _bt(softwareserial(rx, tx)) {} 

errors with

error: invalid initialization of non-const reference of type 'softwareserial&' rvalue of type 'softwareserial' 

the last thing tried moving initialization inside of first constructor so:

serverlib::serverlib(int rx, int tx, string name, string game) {     _bt = softwareserial(rx, tx);     _bt.begin(9600); } 

but results in

error: uninitialized reference member 'serverlib::_bt' [-fpermissive] 

in c# you're passing serial reference in c++ copy. you're getting brand new serial object presumably isn't "open".

i make _bt std::unique_ptr, create _bt = std::make_unique , pass (with std::move) or use std::shared_ptr if it's needed elsewhere.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -