Go Down

Topic: Use "Serial_ Serial;" as parameter for a new class (Read 465 times) previous topic - next topic

chlor

Can the predefined variable "Serial" be used as parameter for a new class?

It should be possible to use a statement like this:
console.clearScreen();
and the initialization could look like:
AnsiTerm console(Serial);
(maybe with some pointers instead (I have tried))

Here is my code:
Code: [Select]

#include <Stream.h>

class AnsiTerm {
  public:
    AnsiTerm(Stream);
    clearScreen();
  private:
    Serial_ _stream;
};

AnsiTerm::AnsiTerm(Stream useStream)
{
  _stream = useStream;
}

AnsiTerm::clearScreen()
{
  _stream.print(F("\e[2J"));
}

AnsiTerm console(Serial);

void setup() {
  Serial.begin(9600);
  console.clearScreen();
}

void loop() {
}


The Stream class says it misses some overloading, which make sence. So I tried to use the Serial_ class but it gave other errors.

I have made this construction before in C++, but then the whole code was designed with that in purpose. Here I want to use the existing "Serial" variable.

Whandall

#1
Apr 02, 2017, 01:41 pm Last Edit: Apr 02, 2017, 01:43 pm by Whandall Reason: changed include back
Code: [Select]
#include <Stream.h>

class AnsiTerm {
  public:
    AnsiTerm(Stream& useStream) : _stream(useStream) {
    }
    void clearScreen() {
      _stream.print(F("\e[2J"));
    }
  private:
    Stream& _stream;
} console(Serial);

void setup() {
  Serial.begin(9600);
  console.clearScreen();
}

void loop() {}
Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. (D.Adams)

chlor

Wow, that was compact! It is actually working!

Can you explain this one:
AnsiTerm(Stream& useStream) : _stream(useStream) {}
How come that this does the assignment I tried to do? I mean you don't have any
_stream = useStream;
in your code.

Does the colon-assignment above have a name, like early-binding or so?

(I guess I have to read more C++ stuff..)

Whandall

#3
Apr 02, 2017, 02:33 pm Last Edit: Apr 02, 2017, 02:37 pm by Whandall
You can not assign to references, but you can initialize them, that's what the : <initlist> does.

http://en.cppreference.com/w/cpp/language/initializer_list

You tried to throw whole classes around, not references or pointers to them.
Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. (D.Adams)

Go Up