如何在抽象类的成员函数中使用/转换对“this”的引用?

时间:2016-04-08 18:53:58

标签: c++ inheritance arduino this abstract-class

以下代码效果很好......

 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的公共成员函数中使用这个新发现的可印刷性..

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'

等等......但是为什么编译器找不到“候选者”(在同一个Print标题中,Serial是其中的子类)...

size_t println(const Printable&);

甚至

size_t println(void);

我已经尝试了每一个演员this我能够在没有任何魔法的情况下唤起我。是否根本无法使用this调用抽象类函数?

对于那些吵着要compilable example... here you are的人。

1 个答案:

答案 0 :(得分:1)

因为你表示

locationid = 5706bbc7b47a0b25981d3a40
reviewid = 5706bd65b47a0b25981d3a41
reviews = { author: 'Simon Holmes',
  id: 5706bd65b47a0b25981d3a41,
  rating: 5,
  timestamp: Tue Jul 16 2013 00:00:00 GMT+0100 (BST),
  reviewText: 'What a great place. I can\'t say enough good things about it.',
  createdOn: Fri Apr 08 2016 19:50:15 GMT+0100 (BST) },{ author: 'Jon M',
  id: 5706bda2b47a0b25981d3a42,
  rating: 5,
  timestamp: Tue Sep 09 2014 00:00:00 GMT+0100 (BST),
  reviewText: 'Meh...',
  createdOn: Fri Apr 08 2016 19:50:15 GMT+0100 (BST) }
#0.rating =  5
#0.id =  null
returned review = null
GET /api/locations/5706bbc7b47a0b25981d3a40/reviews/5706bd65b47a0b25981d3a41 404 34.468 ms - 32

有效,我打算猜测你需要:

void loop() { Serial.println(pp); }

void print() { Serial.println(*this); } // ^^ Need * before "this" 是指向当前对象的指针。 this是它指向的对象。