MyProject.ino
:
#include "MyClass.h"
void setup()
{
Serial.begin(9600);
// MyClass.MyStaticMethod();
MyClass::MyStaticMethod();
}
Both uncommented lines work, but the commented (when uncommented, of course) results in this error: expected unqualified-id before '.' token
.
Now, I know this is because of the incorrect scope-resolution. Yet, how come Serial
manages to call static functions without the need to use ::
to correction to scope-resolution.
How come MyClass.MyStaticMethod()
doesn't work, but Serial.begin()
does?
1 Answer 1
.
is used to call a method on a class instance whereas ::
is used to call a static method within a class itself.
There is no Serial
class - Serial
is merely an instance of the HardwareSerial
class.
#if defined(UBRRH) && defined(UBRRL)
HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
#else
HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
#endif
If you want to use .
then you have to instantiate your class and not use a static method:
class MyClass {
static void myStaticMethod() {
}
void myMethod() {
}
};
MyClass Fred;
// ...
Fred.myMethod();
MyClass::myStaticMethod();
-
Ah. That was quite the misnomer since instances are usually with a lower case. I thought it was a class. :)Fine Man– Fine Man2016年12月02日 22:20:16 +00:00Commented Dec 2, 2016 at 22:20
-
1That is the normal way, yes - but since when have Arduino done things normally? ;)Majenko– Majenko2016年12月02日 22:21:00 +00:00Commented Dec 2, 2016 at 22:21
-
If a newcomer (myself) is just beginning to see abnormalities, I can't imagine how many you've found. :)Fine Man– Fine Man2016年12月02日 22:22:11 +00:00Commented Dec 2, 2016 at 22:22