如何在抽象 class 成员函数中 use/cast 对 "this" 的引用?
How to use/cast a reference to "this" in an abstract class' member function?
以下代码效果很好...
class Printable { public:
virtual size_t printTo(Print& p) const = 0;
};
class Printer : public Printable { public:
size_t printTo(Print& p) const {
return p.print("I am a printer");
}
};
Printer pp;
void loop() { Serial.println(pp); }
I am a printer
....
但是,如果我尝试在 Printer
的 public 成员函数中使用这个新发现的可打印性。.
void print() { Serial.println(this); }
变砖了...
error: call of overloaded 'println(Printer* const)' is ambiguous
note: candidates are:
size_t Print::println(char) <near match>
note: no known conversion for argument 1 from 'Printer* const' to 'char'
size_t Print::println(unsigned char, int) <near match>
note: no known conversion for argument 1 from 'Printer* const' to 'unsigned char'
size_t Print::println(int, int) <near match>
note: no known conversion for argument 1 from 'Printer* const' to 'int'
等等,等等...但是为什么编译器没有找到 "candidate"(在同一个 Print
header 中,其中 Serial
是一个子class 的)...
size_t println(const Printable&);
甚至
size_t println(void);
我已经尝试了所有我能唤起的 this
施法,没有任何魔法。是否根本不可能用 this
调用抽象 class 函数?
对于所有吵着要 compilable example... here you are 的人。
因为你指出
void loop() { Serial.println(pp); }
有效,我将大胆猜测您需要:
void print() { Serial.println(*this); }
// ^^ Need * before "this"
this
是指向当前对象的指针。 *this
是它指向的对象。
以下代码效果很好...
class Printable { public:
virtual size_t printTo(Print& p) const = 0;
};
class Printer : public Printable { public:
size_t printTo(Print& p) const {
return p.print("I am a printer");
}
};
Printer pp;
void loop() { Serial.println(pp); }
I am a printer
....
但是,如果我尝试在 Printer
的 public 成员函数中使用这个新发现的可打印性。.
void print() { Serial.println(this); }
变砖了...
error: call of overloaded 'println(Printer* const)' is ambiguous
note: candidates are:
size_t Print::println(char) <near match>
note: no known conversion for argument 1 from 'Printer* const' to 'char'
size_t Print::println(unsigned char, int) <near match>
note: no known conversion for argument 1 from 'Printer* const' to 'unsigned char'
size_t Print::println(int, int) <near match>
note: no known conversion for argument 1 from 'Printer* const' to 'int'
等等,等等...但是为什么编译器没有找到 "candidate"(在同一个 Print
header 中,其中 Serial
是一个子class 的)...
size_t println(const Printable&);
甚至
size_t println(void);
我已经尝试了所有我能唤起的 this
施法,没有任何魔法。是否根本不可能用 this
调用抽象 class 函数?
对于所有吵着要 compilable example... here you are 的人。
因为你指出
void loop() { Serial.println(pp); }
有效,我将大胆猜测您需要:
void print() { Serial.println(*this); }
// ^^ Need * before "this"
this
是指向当前对象的指针。 *this
是它指向的对象。