我从here获得了代码。

class Timer {
 public:
  Timer();
};

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

  int get_time()
  {
      return 1;
  }
};

int main() {
  TimeKeeper time_keeper(Timer());
  return time_keeper.get_time();
}

从外观上看,由于以下原因,它应该会出现编译错误:
TimeKeeper time_keeper(Timer());

但是,只有存在return time_keeper.get_time();时,它才会发生。

为什么这行甚至很重要,编译器也会在time_keeper(Timer() )构造上发现歧义。

最佳答案

这是由于TimeKeeper time_keeper(Timer());被解释为函数声明而不是变量定义。就其本身而言,这不是一个错误,但是当您尝试访问time_keeper的get_time()成员(它是一个函数,而不是TimeKeeper实例)时,编译器将失败。

这是您的编译器如何查看代码:

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();
}

关于c++ - 最烦人的解析,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5926103/

10-13 07:05