Most vexing parse

后端 未结 1 1759
逝去的感伤
逝去的感伤 2020-11-21 23:39

I got the code from here.

class Timer {
 public:
  Timer();
};

class TimeKeeper {
 public:
  TimeKeeper(const Timer& t);

  int get_time()
  {
      ret         


        
1条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 00:24

    This is due to the fact that TimeKeeper time_keeper(Timer()); is interpreted as a function declaration and not as a variable definition. This, by itself, is not an error, but when you try to access the get_time() member of time_keeper (which is a function, not a TimeKeeper instance), your compiler fails.

    This is how your compiler view the code:

    int main() {
      // time_keeper gets interpreted as a function declaration with a function argument.
      // This is definitely *not* what we expect, but from the compiler POV it's okay.
      TimeKeeper time_keeper(Timer (*unnamed_fn_arg)());
    
      // Compiler complains: time_keeper is function, how on earth do you expect me to call
      // one of its members? It doesn't have member functions!
      return time_keeper.get_time();
    }
    

    0 讨论(0)
提交回复
热议问题