最麻烦的解析

发布于 2024-11-05 13:37:36 字数 577 浏览 1 评论 0原文

我从此处获取了代码。

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() ) 构造上的歧义。

I got the code from 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();
}

From the looks of it, it should get compile error due to the line:

TimeKeeper time_keeper(Timer());

But it only happens if return time_keeper.get_time(); is present.

Why would this line even matter, the compiler would spot ambiguity on time_keeper(Timer() ) construction.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回心转意 2024-11-12 13:37:36

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

这是编译器查看代码的方式:

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

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文