C++ syntax question - Defining an object in a class that requires arguments?
-
I need some help with how to properly define an object in a class as a public object of the class for objects that require arguments. I would like to hardcode the arguments. For example I want to make the second UART port in a class and hardcode the UART to 2.
.h file for class
#ifndef TestClass_h #define TestClass_h #include "Arduino.h" #include <M5Unified.h> class TestClass { public: //-- Define RS458 to UART to UART2, HardwareSerial needs a UART number passed to it -- //What I have tried, I would like to hardcode the UART number to 2. How do I do this????? HardwareSerial SerialRS485; // 1 - Does not compile, I need something in the .cpp file to make this work HardwareSerial SerialRS485(uint8_t _uart); // 2 - Can get this to compile but then does not compile if I use a uncomment the test funciton HardwareSerial SerialRS485(uint8_t 2); // 3 - Does not compile //constructor TestClass(); //Functions - Main void testFunction(); private: uint16_t _private1 = 0; }; #endif.cpp file for class
#include "TestClass.h" #include "Arduino.h" //Constructor def TestClass::TestClass() { } void TestClass::testFunction() { Serial.println("USB Serial Port"); SerialRS485.println("RS485 Serial Port"); }main ino file
#include "Arduino.h" #include <M5Unified.h> //For M5Stack ESP Hardware //Create test class #include "TestClass.h" TestClass TestObject; void setup(void) { auto cfg = M5.config(); //M5 Unified config M5.begin(cfg); delay(500); } void loop(void) { M5.update(); //Update button state TestObject.testFunction(); delay(1000); } -
@lukes said in C++ syntax question - Defining an object in a class that requires arguments?:
HardwareSerial
Maybe this solves your problem ...
class StaticClass { private: int myContent; public: StaticClass(int v){myContent = v;} void printout(){printf("%d\n",myContent);} }; class TestClass { public: //StaticClass myClass = StaticClass(42); // With C11 StaticClass myClass; TestClass() : myClass(42) { } void doit() { myClass.printout(); } }; int main(void) { TestClass tc; tc.doit(); }
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login