c++ - 最烦人的解析

标签 c++ most-vexing-parse

我从 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/35254920/

相关文章:

python - xtensor 和 xsimd : improve performance on reduction

c++ - 如何继承成员函数以便它始终返回对派生实例的引用?

c++ - 如何在 C/C++ 中读/写任意位

c++ - 在模板参数列表中转发声明类型名

c++ - 从 'Type (__cdecl *)(std::istream)' 到 'Type &' 的转换

C++ 声明一个函数而不是调用一个复杂的构造函数

c++ - 将指向成员函数的指针作为指向函数的指针传递

c++ - 使用意外声明为函数的对象后解释 GCC 错误

c++ - 使用 std::string 和 char* 的最烦人的解析实例

c++ - 关于最令人烦恼的解析的一个令人困惑的细节